Game Pass (IAP side): $5 weekly pass across all nine games + account-wide POL cap service
- gamepass.js: durable pass store, waiting orders fulfilled by the next $5 package, cap ledger (daily/total per Central day, progress deferral + next-day carry-forward, idempotent refs kept 90 days, void), weekly Pass Tournament (Monday 9 AM Central, marks.claim, prizes recorded for the game faucets), admin stats. Settings in site config, caps enforced only from capsStartDate (recorded before). - server.js: /api/partner/player, /api/partner/polgrant(+/void), /api/partner/tournament/pending|paid, /api/my/gamepass(+/buy), /api/admin/gamepass/stats|comp|tournament/run; gamePass claim on every sign-in hand-off token; purchase-event fulfilment inside the marks.claim block. - Members > Games: Game Pass card (Buy via IAP.confirmBox, deep link /my#games?pass=1), Overview nudge after a free-cap hit. Admin > Game Pass pane. Chatbot canned answer + FACTS, KNOWLEDGE_DATE 10-16. - qa/gamepass.mjs scripted test (bash qa/run.sh gamepass), Games tab card in qa/walk.mjs. - docs/GAME-PASS.md: 3a clarifications + Built section; docs/GAME-PASS-RELEASE.md draft (not sent). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
+4
-1
@@ -20,8 +20,10 @@ function key() {
|
||||
function enabled() { return !!key(); }
|
||||
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
const KNOWLEDGE_DATE = '2026-10-15'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const KNOWLEDGE_DATE = '2026-10-16'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const CANNED = [
|
||||
{ re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i,
|
||||
a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the Pass badge. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' },
|
||||
{ re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i,
|
||||
a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' },
|
||||
{ re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i,
|
||||
@@ -160,6 +162,7 @@ FACTS:
|
||||
- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through <date>', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends.
|
||||
- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin.
|
||||
- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members.
|
||||
- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL NINE games (linked positions share it). Paid with 500 PURCHASED-grade credits (ads.gamePurchase purchasedOnly, the PolyWarriors mint rule; earned credits never buy a pass); with no purchased credits the pass waits and a $5 package bought meanwhile starts it automatically (the member keeps the package credits). Buying while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit.
|
||||
- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts.
|
||||
- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed.
|
||||
- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility.
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Release note draft: the Game Pass (not sent)
|
||||
|
||||
Status: DRAFT for Marty's review. Nothing below has been posted, emailed or published. Dates are placeholders until the caps start
|
||||
date is set in Admin > Settings (`capsStartDate`) and `gamePassEnabled` is switched on.
|
||||
|
||||
## Short version (Telegram / feed)
|
||||
|
||||
The games now have a Game Pass: $5 for 7 days, all nine games on one account. Free play keeps paying real POL every day. The Pass
|
||||
plays more: higher daily caps across every game, a seat in the weekly Pass Tournament with POL prizes, extra plays or a perk in each
|
||||
game, and the Pass badge. Members > Games > Game Pass. From [DATE] the daily POL caps are account-wide: free play 0.30 POL a day on
|
||||
repeatable rewards and 2 POL a day in all; with the Pass 1.50 and 5. One-time rewards you earn over the cap are never lost; they pay
|
||||
over the next days.
|
||||
|
||||
## Release note (Admin > Releases, member-facing)
|
||||
|
||||
**The Game Pass: more game across all nine games**
|
||||
|
||||
Every member earns real POL in our games, and that does not change. What is new:
|
||||
|
||||
- **The Game Pass.** $5 for 7 days, one pass for your whole account (linked positions share it), covering PolHunter, Gem Kingdom,
|
||||
SpellWheel, PolyWarriors, Road Agent, ClutterHunt, PolyBreak, Drip Runner and Spooky Doors while its season runs.
|
||||
- **What it does.** Higher daily POL caps in every game (1.50 POL a day on repeatable play instead of 0.30, and 5 POL a day in all
|
||||
instead of 2), a place in the weekly **Pass Tournament**, extra plays or a perk in each game (more PolHunter missions, a free
|
||||
continue in Gem Kingdom, a free hint in SpellWheel and ClutterHunt, an extra patrol in Road Agent, a starting shield in Drip
|
||||
Runner, an extra paddle in PolyBreak, an extra mission in PolyWarriors, an extra door in Spooky Doors), and the Pass badge.
|
||||
- **How to get it.** Members > Games > Game Pass. It costs 500 purchased credits, the credits from a package you bought. If you
|
||||
have none, buy a $5 package and the pass starts the moment it settles; you keep every credit of that package for your ads. Buying
|
||||
while a pass is active adds 7 days.
|
||||
- **Account-wide daily caps, from [DATE].** Until now each game had its own daily limit. From [DATE] the limit is one number for
|
||||
your whole account across all the games, reset at midnight Central: free play 0.30 POL a day on repeatable rewards (finds, daily
|
||||
puzzles, patrols, gems, drips) and 2 POL a day for everything; with the Pass 1.50 and 5. A one-time reward (a boss, a chapter, a
|
||||
sector, a room) never changes and is never lost: whatever is over the day's total carries to the next day until it is paid in
|
||||
full. A 10 POL boss still pays 10 POL, over a few days.
|
||||
- **The weekly Pass Tournament.** Monday to Sunday, Central time, pass holders are ranked by their plays across all the games. The
|
||||
prize pool is 5% of that week's pass sales, paid in POL to the top three (50 / 30 / 20) and posted in Game Achievements on
|
||||
Monday morning.
|
||||
|
||||
The Pass does not change what any reward pays. Free play pays; the Pass plays more.
|
||||
|
||||
## Announcement timing
|
||||
|
||||
- One week before `capsStartDate`: post the short version, publish this note, switch `gamePassEnabled` on so members can buy
|
||||
ahead of the caps.
|
||||
- On `capsStartDate`: the caps enforce themselves at midnight Central; nothing to deploy.
|
||||
- First Monday 9 AM Central after launch: the first tournament settles and posts by itself (only while `gamePassEnabled` is on).
|
||||
|
||||
## Wording rules (chatbot, posts, pages)
|
||||
|
||||
Never "earn more", "pays for itself", "income". Always "free play pays; the Pass plays more". Reward amounts never change with the
|
||||
Pass. Caps are per account, per Central day. Deferred progress rewards are "paid over the next days", never "lost".
|
||||
@@ -0,0 +1,214 @@
|
||||
# Game Pass: draft spec (2026-10-16)
|
||||
|
||||
Marty's direction (10-16): a $5 weekly Game Pass that covers all nine games and raises the daily POL cap; a tighter
|
||||
free cap so nobody farms the games all day for free. Pass = "more game", never pitched as payback. Free play keeps
|
||||
paying real POL (the "paid before they ever pay" funnel in the presentation, deck and guide).
|
||||
|
||||
## 1. What the games pay today (live settings, 7-day earnings to 2026-10-16)
|
||||
|
||||
Two kinds of POL rewards exist in every game:
|
||||
|
||||
- **Progress rewards**: one-time per account (first clear of a stage, boss, sector, rival, chapter, room). Finite.
|
||||
- **Daily play rewards**: repeatable every day (finds, daily puzzle, patrol, gems, drips). This is the "all day" risk.
|
||||
|
||||
| Game | Progress rewards (one-time, POL) | Daily play rewards (repeatable) | Game cap/day | Players (7d) | Median / p90 / max per player-day | POL out / week |
|
||||
|---|---|---|---|---|---|---|
|
||||
| PolHunter | none | finds 0.05-1.00 (skewed small), 3 missions/day | 40 | 38 | 0.48 / 0.97 / 4.04 | **102.1** |
|
||||
| Gem Kingdom | stages 0.02-0.15; bosses 0.25 / 0.5 / 2 / 5 / 7.5 / **10** | none | 40 | 25 | 0.46 / 11.35 / **25.49** | **101.4** |
|
||||
| SpellWheel | levels 0.02-0.05; chapters 0.25-1 | daily puzzle 0.03, streak 0.15 | 20 | 102 | 0.04 / 0.16 / 1.50 | 17.6 |
|
||||
| Spooky Doors (to Oct 31) | ladder 0.1 / 0.25 / 0.5 / 1 / 2 | none | 25 | 11 | 0.85 / 1.00 / 2.00 | 10.7 |
|
||||
| PolyWarriors | rivals 0.02-0.10, ladder 0.5, elite 0.12-0.5, elite clear 2 | none (PvP pays Circuits) | 20 | 10 | 0.18 / 1.09 / 4.94 | 8.8 |
|
||||
| ClutterHunt | per room: clear 0.05, 3-star 0.05, expert 0.15, expert stars 0.10 | none | 20 | 13 | 0.20 / 0.95 / 1.05 | 6.4 |
|
||||
| PolyBreak | rounds 0.02 / 0.03 / 0.05 | gems 0.01-0.15, up to 0.5/day | 5 | 39 | 0.02 / 0.06 / 0.12 | 1.3 |
|
||||
| Drip Runner | chapters | drips 0.05, items | 5 | 15 | 0.05 / 0.15 / 0.25 | 1.2 |
|
||||
| Road Agent | sectors 0.05-1.00 (3.60 total) | patrol 0.03/day | 25 | 5 | 0.08 / 0.16 / 0.16 | 0.5 |
|
||||
| **All games** | | | | | | **~250 POL/week (~$23 at 9c)** |
|
||||
|
||||
PolHunter and Gem Kingdom are 81% of the burn. PolHunter is repeatable play (and every find is a delivered sponsor
|
||||
visit, so that burn delivers advertiser inventory). Gem Kingdom's burn is its boss amounts: one player took 25.5 POL in
|
||||
a single day. No other game pays more than 2 POL for any single reward.
|
||||
|
||||
## 2. The pass
|
||||
|
||||
- **$5, 7 days, all nine games.** One pass per account; buying while active extends by 7 days.
|
||||
- Paid with **purchased-grade credits only** (500 credits = the $5 package), through the existing game-purchase path
|
||||
(`ads.gamePurchase` with `purchasedOnly`, the same rule as PolyWarriors mint passes). A $5 package bought while a pass
|
||||
order waits fulfils it (the `pwpasses` pattern). Earned credits never buy a pass, or no money enters and the pass is
|
||||
just a free cap increase.
|
||||
- Money flow is the normal on-chain split of the $5 package: $2.50 sponsor, $1.00 level 2, $0.50 level 3, $1.00 company.
|
||||
The company's $1 is what funds the extra POL; the games' 30% pool-share rule is an allowance, not cash.
|
||||
|
||||
## 3. Caps (account-wide, across all nine games)
|
||||
|
||||
| | Free | Pass |
|
||||
|---|---|---|
|
||||
| Daily play rewards (repeatable) | **0.30 POL/day** | **1.50 POL/day** |
|
||||
| Everything (progress + daily), paced | **2.0 POL/day** | **5.0 POL/day** |
|
||||
| Progress rewards | unchanged amounts for everyone; excess over the daily total **carries to the next day** (never lost) | same |
|
||||
|
||||
Why these numbers:
|
||||
- Free 0.30/day sits under PolHunter's median (0.48) and SpellWheel's p90 (0.16 stays free). The regular PolHunter
|
||||
hunter is the natural pass buyer; the casual SpellWheel player never notices.
|
||||
- Pass 1.50/day is above today's p90 for every game, so a pass holder keeps everything they earn today and more.
|
||||
Max repeatable per pass week = 10.5 POL (~$0.98), so the pass can never pay for itself and multi-accounting can't win.
|
||||
- The paced total cap stops the Gem Kingdom spike (25 POL in a day) without changing any reward amount: a 10 POL boss
|
||||
still pays 10 POL, over a few days.
|
||||
- Company per pass: $1.00 in, at most $0.98 out if a holder maxes the repeatable cap every day. Realistic use (about
|
||||
half) nets about $0.50 a pass. Progress rewards were payable to free players already, so the pass adds no cost there.
|
||||
|
||||
**DECIDED (Marty, 2026-10-16): Gem Kingdom's bosses stay at 5 / 7.5 / 10 POL.** "We need one that pays out bigger like
|
||||
that anyway." The paced total cap spreads a big boss payout over a few days; the amounts do not change.
|
||||
|
||||
## 3a. API contract (both sides build to this)
|
||||
|
||||
> **Built 2026-10-16 (IAP side). Clarifications and additions to this contract, none of them breaking:**
|
||||
>
|
||||
> 1. **Where the endpoints live.** `GET /api/partner/player` exists today on each GAME (IAP reads the player's card line from it).
|
||||
> The pass and caps version below is served by **IAP** (`https://instantadpay.com/api/partner/player`), so a game CALLS it; nothing
|
||||
> changes on the game's own endpoint. Same for `polgrant`, `polgrant/void` and `tournament/*`: all on IAP.
|
||||
> 2. **Signature, spelled out.** Each game signs with the shared secret it already holds (its `*_SSO_SECRET`; PolHunter uses
|
||||
> `HUNT_SSO_SECRET`). 10-minute window on `ts` (ms).
|
||||
> - `GET /api/partner/player?game=<slug>&m=<memberId>&e=<email>&ts=<ms>&sig=<hex>` with
|
||||
> `sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts)`, `who` = memberId when > 0, else the lowercased email (the same string
|
||||
> the games already compute for IAP's calls to them, with `game` added so IAP knows which secret to check).
|
||||
> - `POST` endpoints: JSON body that includes `game: <slug>`, headers `X-Game-Ts: <ms>` and
|
||||
> `X-Game-Sig: HMAC-SHA256(secret, ts + '\n' + rawBody)` hex (sign the exact bytes you send).
|
||||
> - `GET /api/partner/tournament/pending?game=<slug>&ts&sig` with `who = 'tournament'`.
|
||||
> 3. **`email` is accepted beside `memberId`.** Players who have not linked a wallet have `memberId: 0` in every hand-off token; send
|
||||
> `email` too (the token has it) and IAP resolves the account by email. A linked position's member id resolves to the owner's
|
||||
> account: the pass and the caps are per ACCOUNT.
|
||||
> 4. **Extra fields in answers** (additive): `polgrant` also returns `carried` (POL paid from an earlier day's deferral, already
|
||||
> inside `allowed`), `capHit` (`'daily'|'total'|null`), `enforced` (false before `capsStartDate`), `repeat` (true when the ref was
|
||||
> already answered), `voided`. `caps` also has `enforced`, `pass` and `pending` (POL deferred for this game, not yet paid).
|
||||
> `player` also returns `memberId, username, wallet, suspended, gamePassEnabled`. A suspended account gets `allowed: 0,
|
||||
> suspended: true` and nothing is recorded (a cleared account can replay the ref).
|
||||
> 5. **Carry-forward counts against the later day's total cap** (that is what "paced" means): a 10 POL boss on a 2 POL/day free
|
||||
> account pays 1.7-2.0 a day until done, paid before that day's new grants. Carry-forward only happens on a LATER Central day
|
||||
> than the deferral and only to the same game; the reply that carries it says `carried`.
|
||||
> 6. **`void` reverses only that ref's own share** (its `allowed` on its day and whatever of its deferral is still queued). POL it
|
||||
> already caused to be carried on a later day belongs to that later day and stays. The ref remains answered as voided.
|
||||
> 7. **Hand-off tokens carry the flag** as `gamePass: { active, until }` (not `pass`, which the in-game sign-in flow already uses for
|
||||
> its session token). Apply perks from it at sign-in; refresh from `player`/`polgrant` answers.
|
||||
> 8. **Tournament prize payout seam.** IAP records the winners and POL amounts; a game faucet (Road Agent pattern) pays them:
|
||||
> `GET /api/partner/tournament/pending` lists `{ week, place, email, memberId, wallet, pol }` rows still unpaid, and the paying
|
||||
> game calls `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. Which faucet pays is a
|
||||
> settings/ops decision, not yet wired: until it is, Admin > Game Pass shows the unpaid rows.
|
||||
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
|
||||
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skips the credit charge.
|
||||
|
||||
IAP is the single source of truth for the pass and for the account-wide caps. Every game already signs partner calls
|
||||
with its shared secret (the `/api/partner/player` pattern); the new calls use the same auth.
|
||||
|
||||
- `GET /api/partner/player?...` (existing) additionally returns `pass: { active: bool, until: ms|null }` and
|
||||
`caps: { daily: n, total: n, used: { daily: n, total: n }, day: 'YYYY-MM-DD' }` (Central day).
|
||||
- `POST /api/partner/polgrant` body `{ memberId, game, kind: 'daily'|'progress', pol, ref }` (ref = the game's own
|
||||
idempotency key, e.g. `sector:3`, `find:<id>`). Response `{ allowed: n, deferred: n, pass: bool, day }`.
|
||||
- `kind: 'daily'`: `allowed = min(pol, dailyCapRemaining, totalCapRemaining)`, the rest is DROPPED (never deferred).
|
||||
- `kind: 'progress'`: `allowed = min(pol, totalCapRemaining)`, the rest is DEFERRED: IAP stores it and the game's
|
||||
next call (any kind) on a later day gets it added to `allowed` first (carry-forward). Nothing is ever lost.
|
||||
- Same `ref` twice = same answer (idempotent). Fail closed: if the game cannot reach IAP it grants nothing and retries
|
||||
the same ref later.
|
||||
- `POST /api/partner/polgrant/void` `{ memberId, game, ref }` when a game decides not to pay after all (rare).
|
||||
- Settings on IAP (Admin > Settings, no deploy): `gamePassEnabled`, `gamePassPriceCredits` (500), `gamePassDays` (7),
|
||||
`capFreeDaily` 0.30, `capFreeTotal` 2.0, `capPassDaily` 1.50, `capPassTotal` 5.0, `capsStartDate` (the free caps apply
|
||||
only from this Central date; before it, the games' own caps stand, so the change can be announced a week ahead),
|
||||
`passTournamentPct` 5.
|
||||
- Pass purchase: `POST /api/my/gamepass/buy` spends 500 purchased-grade credits (`ads.gamePurchase` with
|
||||
`purchasedOnly`); a $5 package bought while a pass order waits fulfils it (the `pwpasses` pattern). Buying while active
|
||||
extends `until` by 7 days. The Games tab shows the card, the state, and the expiry.
|
||||
- Games get the pass flag at the sign-in hand-off and on every `polgrant` response; apply perks locally.
|
||||
|
||||
## 4. Pass perks per game (more game, not more payback)
|
||||
|
||||
| Game | Pass perk (besides the higher caps) |
|
||||
|---|---|
|
||||
| PolHunter | 5 missions/day instead of 3; Ad Detective twice a day. Finds still require the sponsor visit. |
|
||||
| Gem Kingdom | one free continue per day (small, so Crowns sales are not undercut) |
|
||||
| SpellWheel | streak bonus 0.15 -> 0.30; one free hint a day |
|
||||
| PolyWarriors | +1 daily mission; defense pay 15 -> 25 Circuits; Pass mark on the warrior card |
|
||||
| Road Agent | 2 patrols/day; +25% scrap. Fuel stays a sponsor visit. |
|
||||
| ClutterHunt | 2 free hints a day |
|
||||
| PolyBreak | gem cap 0.5 -> 1.5/day; one extra paddle per round |
|
||||
| Drip Runner | a shield at the start of every run |
|
||||
| Spooky Doors | +1 door a day while the season runs |
|
||||
| All games | **Weekly Pass Tournament**: cross-game leaderboard (finds, clears, wins), prizes from 5% of pass sales (25c per pass) in POL; Pass badge; gold profile frame |
|
||||
|
||||
Ad-visit mechanics (fuel, Crowns, hints, refuels) stay as they are. Those verified visits are what advertisers pay for.
|
||||
|
||||
## 5. Build outline
|
||||
|
||||
1. **IAP (central):** durable `gamepass` map {email: {until, history}}; `GET /api/partner/player` returns `pass:{active, until}`;
|
||||
new `POST /api/partner/polgrant` {member, game, kind: progress|daily, pol} -> {allowed, deferred} enforcing the
|
||||
account-wide caps (fail closed when IAP is unreachable; games retry); Games tab card "Game Pass: $5 for 7 days, all
|
||||
games"; buy flow via purchased credits or the $5 package; admin: passes sold, POL out per pass, cap hits.
|
||||
2. **Each game:** read the pass flag at the sign-in hand-off; call `polgrant` before every POL grant (replaces each game's
|
||||
own `dailyCapPol` for the account-wide rule; keep the local cap as a backstop); pace deferred progress rewards (queue,
|
||||
pays out next day); apply its perk; show "Pass" state and a "Get the Pass" nudge when the free cap is hit.
|
||||
3. **Tournament:** weekly job on IAP ranks pass holders across games, pays prizes from the games' wallets, posts to the
|
||||
Game Achievements topic.
|
||||
4. **Chatbot, release note, presentation games slide, and the guide's games section**: say "free play pays; the Pass
|
||||
plays more" (never "earn more").
|
||||
5. **QA:** iap-qa plus a scripted run per game: free cap hit -> nudge; pass bought -> cap raised; progress reward over
|
||||
the cap -> paid the next day; pass expiry -> back to free caps.
|
||||
|
||||
## 6. Rollout
|
||||
|
||||
- Announce one week ahead (the free cap change affects today's PolHunter regulars). First week: pass at $5 with a
|
||||
launch tournament; watch passes sold, POL out per pass, free-tier burn, verified visits delivered.
|
||||
- Review after 14 days against: company net per pass >= $0.40, free burn under 150 POL/week, no drop in visit deliveries.
|
||||
|
||||
## Built (IAP side, 2026-10-16)
|
||||
|
||||
Everything below is on IAP, behind `gamePassEnabled` (default off). The caps are recorded from day one and ENFORCED only from
|
||||
`capsStartDate`, so the change can be announced a week ahead and Admin can read what the caps would have done meanwhile.
|
||||
|
||||
**Files**
|
||||
- `gamepass.js` (new): pass store, waiting orders, cap ledger (`DATA_DIR/gamepass-ledger.json`, refs kept 90 days), tournament,
|
||||
admin stats, prune. Durable persisted maps `gamepass`, `gporders`, `gpprizes` (added to the DURABLE set in server.js so a deploy
|
||||
never wipes them).
|
||||
- `server.js`: settings defaults, init + hourly tournament tick + 6-hourly prune, purchase-event fulfilment (inside the
|
||||
`marks.claim` block, so two app copies never double-fulfil), partner helpers (`GP_SECRETS`, `gpPartnerCheck`, `gpResolve`,
|
||||
`gpDevNow`), `polUsdLive()` (catalog rate, 10-minute cache), `gpClaim` (the `gamePass` claim on every sign-in hand-off token,
|
||||
including PolHunter's), and the endpoints below.
|
||||
- `public/my.html` + `public/assets/my.js`: the Game Pass card at the top of Members > Games (state, caps line, Buy/Extend with
|
||||
`IAP.confirmBox`, waiting state with a Buy-a-package button), deep link `/my#games?pass=1` (setPane now strips a `?query` from
|
||||
the hash and highlights the card), the Overview nudge card `gpNudge` (shown once a day per browser after a game reports a free-cap
|
||||
hit, never to pass holders). Asset tag bumped to `my.js?v=20261016a`.
|
||||
- `public/admin.html` + `public/assets/admin.js`: Admin > Game Pass pane (passes sold week/total, active, POL out per pass week,
|
||||
free/pass cap hits, deferred queue, tournament last run + unpaid prizes, "Settle last week now", comp a pass). Tag
|
||||
`admin.js?v=20261016gp`.
|
||||
- `chatbot.js`: canned answer + FACTS line, `KNOWLEDGE_DATE` 2026-10-16.
|
||||
- `qa/gamepass.mjs` (new, `bash qa/run.sh gamepass`), `qa/walk.mjs` (Games tab card on/off + admin pane), `qa/run.sh`.
|
||||
- `docs/GAME-PASS-RELEASE.md`: the member-facing release note draft (not sent).
|
||||
|
||||
**Settings** (Admin > Settings > Site settings; all read live, no deploy): `gamePassEnabled` ('0'), `gamePassPriceCredits` (500),
|
||||
`gamePassDays` (7), `capFreeDaily` (0.30), `capFreeTotal` (2.0), `capPassDaily` (1.50), `capPassTotal` (5.0), `capsStartDate` ('',
|
||||
Central YYYY-MM-DD), `passTournamentPct` (5), `telegramGamesTopicId` ('661565'), `telegramGamesChatId` ('' = the shared echo chat).
|
||||
|
||||
**Endpoints**
|
||||
- Members: `GET /api/my/gamepass` -> `{ enabled, active, until, price, days, usd, waiting, bought, caps, capsStart, lastCapHit,
|
||||
tournament }`; `POST /api/my/gamepass/buy` -> `{ ok, active, until }` or `{ needPay: true, payUrl: '/my?from=gamepass#buy',
|
||||
order, price, need }`. Spends `gamePassPriceCredits` purchased-grade credits through `ads.gamePurchase(purchasedOnly)` with the
|
||||
credit-log label "Game Pass (7 days)"; short = waiting order, fulfilled by the next $5+ package purchase event.
|
||||
- Games (signed, see 3a): `GET /api/partner/player`, `POST /api/partner/polgrant`, `POST /api/partner/polgrant/void`,
|
||||
`GET /api/partner/tournament/pending`, `POST /api/partner/tournament/paid`.
|
||||
- Admin: `GET /api/admin/gamepass/stats`, `POST /api/admin/gamepass/comp { email, why }`,
|
||||
`POST /api/admin/gamepass/tournament/run { week?, force? }`.
|
||||
|
||||
**Tournament job**: hourly tick; once Monday 9 AM Central has passed and the closed week (Mon 00:00 to Mon 00:00 Central) has no
|
||||
row, exactly one app copy (`marks.claim('gamepass-tournament:<week>')`) ranks the week's pass holders by grants reported through
|
||||
`polgrant` (progress and daily weigh the same, one point per ref with pol > 0), pool = `passTournamentPct` of the week's pass sales
|
||||
in USD at the live catalog POL rate, split 50/30/20, rows recorded in `gpprizes` as pending, top 3 posted to the Game Achievements
|
||||
topic (`telegramGamesTopicId`, only when enabled), winners get an inbox notice (kind `notice`). Comps (`/comp`) are passes, not
|
||||
sales. If the POL rate is unavailable the tick retries next hour.
|
||||
|
||||
**Known limits / follow-ups**
|
||||
- The cap ledger is a JSON file on the volume (like the other IAP side stores), not a MySQL table: during the ~30 s deploy overlap
|
||||
two app copies each hold their own copy and the last save wins. A grant answered by the copy that is about to stop could be
|
||||
re-answered fresh by the other on retry. Move `refs`/`days` into MySQL if the games report drift.
|
||||
- `qa/gamepass.mjs` stubs the credit charge (`devPaid`) for the "buy -> active" step: `ads.gamePurchase(purchasedOnly)` needs a
|
||||
position with on-chain package credits, which a local copy without RPC cannot have. The "short -> waiting order -> package fulfils
|
||||
it" step runs the real path. The purchasedOnly charge itself is the live PolyWarriors mint path.
|
||||
- Prize POL is not sent by IAP (see 3a item 8); the Games pane lists unpaid rows until a faucet is wired.
|
||||
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
|
||||
Game Pass keys show in the Site settings form).
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
// Game Pass (2026-10-16): the $5 weekly pass across all nine games, and the account-wide POL cap service the games call
|
||||
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
|
||||
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
|
||||
//
|
||||
// What lives here:
|
||||
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
|
||||
// - waiting orders order -> { status, email, ts, tx } (a $5+ package bought while an order waits fulfils it: the pwpasses pattern)
|
||||
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
|
||||
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
|
||||
// - admin stats
|
||||
//
|
||||
// Not to be confused with the in-game SIGN-IN pass (server.js gamePassMint/gamePassOpen): that is a session token the games keep
|
||||
// in localStorage. This module is the paid Game Pass product. Fields on the wire are `pass: { active, until }` (3a).
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const TZ = 'America/Chicago';
|
||||
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent'];
|
||||
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
|
||||
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
|
||||
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
|
||||
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
|
||||
|
||||
let R = null; // deps from server.js
|
||||
let passes, orders, prizes; // durable persisted maps (server.js open-tokens store, DURABLE set)
|
||||
let L = null; // the cap ledger: { members: { email: { days: {}, deferred: {}, weeks: {} } }, refs: { 'game:ref': {...} } }
|
||||
let saveTimer = null;
|
||||
|
||||
// ---- Central time (no tz lib; same arithmetic as leaderboard.js) ----
|
||||
function ctParts(ts) {
|
||||
const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' });
|
||||
const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s);
|
||||
return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] };
|
||||
}
|
||||
function ctMidnight(ts) { const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000; }
|
||||
function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); return mid - ((p.wd + 6) % 7) * 86400000; }
|
||||
const dayKey = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||
const weekKey = ts => dayKey(weekStart(ts));
|
||||
const dayLabel = key => new Date(key + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
|
||||
|
||||
// ---- settings (Admin > Settings, no deploy) ----
|
||||
function cfg() {
|
||||
const sc = R.siteConfig();
|
||||
const n = (k, d) => { const raw = sc[k]; if (raw === undefined || raw === null || String(raw).trim() === '') return d; const v = Number(raw); return Number.isFinite(v) ? v : d; };
|
||||
const start = String(sc.capsStartDate || '').trim();
|
||||
return {
|
||||
enabled: ['1', 'true', 'on', 'yes'].includes(String(sc.gamePassEnabled).trim().toLowerCase()),
|
||||
price: Math.max(1, Math.round(n('gamePassPriceCredits', 500))),
|
||||
days: Math.max(1, Math.round(n('gamePassDays', 7))),
|
||||
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
|
||||
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
|
||||
start: /^\d{4}-\d{2}-\d{2}$/.test(start) ? start : '',
|
||||
pct: Math.max(0, n('passTournamentPct', 5)),
|
||||
gamesChat: String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(),
|
||||
gamesTopic: String(sc.telegramGamesTopicId || '').trim(),
|
||||
};
|
||||
}
|
||||
const enforcedOn = (c, day) => !!(c.start && day >= c.start);
|
||||
|
||||
// ---- ledger file ----
|
||||
const FILE = () => path.join(R.dataDir, 'gamepass-ledger.json');
|
||||
function load() { try { L = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { L = null; } if (!L || typeof L !== 'object') L = { members: {}, refs: {} }; L.members = L.members || {}; L.refs = L.refs || {}; }
|
||||
function save() { saveTimer = null; try { fs.writeFileSync(FILE(), JSON.stringify(L)); } catch (e) { console.error('gamepass ledger save', e.message); } }
|
||||
function touch() { if (!saveTimer) saveTimer = setTimeout(save, 500); }
|
||||
function member(e) { return (L.members[e] = L.members[e] || { days: {}, deferred: {}, weeks: {} }); }
|
||||
function dayRow(M, day) {
|
||||
return (M.days[day] = M.days[day] || { daily: 0, total: 0, carried: 0, dropped: 0, deferredOut: 0, grants: 0, hits: { daily: 0, total: 0 },
|
||||
tier: { free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 } },
|
||||
would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 } }); // would = what the caps would have done before capsStartDate
|
||||
}
|
||||
|
||||
function init(deps) {
|
||||
R = deps;
|
||||
passes = R.persistedMap('gamepass');
|
||||
orders = R.persistedMap('gporders');
|
||||
prizes = R.persistedMap('gpprizes');
|
||||
load();
|
||||
}
|
||||
|
||||
// ---- the pass ----
|
||||
function rec(e) { return passes.get(e) || null; }
|
||||
function flag(email, now) { const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const until = p && Number(p.until) || 0; return { active: until > t, until: until || null }; }
|
||||
function extend(e, via, extra, now) {
|
||||
const c = cfg(); const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
|
||||
const base = Math.max(t, Number(cur.until) || 0);
|
||||
const until = base + c.days * 86400000;
|
||||
const bought = [Object.assign({ ts: t, via, usd: c.price / 100, days: c.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
|
||||
passes.set(e, Object.assign({}, cur, { until, bought, ts: t }));
|
||||
return { until, days: c.days };
|
||||
}
|
||||
function waitingOrder(e) { for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) return Object.assign({ order: k }, o); return null; }
|
||||
function comp(email, why) { const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }); return { active: true, until: x.until, days: x.days }; } // support comp: counts as no sale
|
||||
|
||||
// GET /api/my/gamepass
|
||||
function view(email, now) {
|
||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e);
|
||||
const caps = capsFor(e, t);
|
||||
return { enabled: c.enabled, active: f.active, until: f.until, price: c.price, days: c.days, usd: c.price / 100,
|
||||
waiting: !!w, waitingSince: w ? w.ts : null, bought: p ? (p.bought || []).length : 0,
|
||||
caps, capsStart: c.start || null, lastCapHit: p && p.lastCapHit && (t - p.lastCapHit.ts) < 2 * 86400000 ? p.lastCapHit : null,
|
||||
tournament: { pct: c.pct, shares: SHARES, next: nextTournamentAt(t) } };
|
||||
}
|
||||
|
||||
// POST /api/my/gamepass/buy. `charge(price, label)` runs ads.gamePurchase(purchasedOnly) and resolves { ok } | { error: 'short', ... } | { error }.
|
||||
async function buy(email, charge, now) {
|
||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
|
||||
if (!c.enabled) return { error: 'The Game Pass is not open yet.' };
|
||||
const r = await charge(c.price, 'Game Pass (' + c.days + ' days)');
|
||||
if (r && r.ok) {
|
||||
const x = extend(e, 'credits', { credits: c.price, campaignId: r.campaignId || null }, t);
|
||||
console.log('gamepass bought with credits', e, c.price, 'until', new Date(x.until).toISOString());
|
||||
return { ok: true, active: true, until: x.until, days: c.days, paid: 'credits' };
|
||||
}
|
||||
if (r && r.error === 'short') {
|
||||
// no purchased-grade credits on a position: the pass waits for a $5 package (bought while the order waits, it fulfils it)
|
||||
let w = waitingOrder(e);
|
||||
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t }); w = Object.assign({ order: k }, orders.get(k)); }
|
||||
return { ok: false, needPay: true, payUrl: '/my?from=gamepass#buy', order: w.order, price: c.price, usd: c.price / 100, available: r.available || 0, need: r.need || c.price,
|
||||
message: 'The pass is paid with purchased credits. Buy a $' + (c.price / 100) + ' package and the pass starts the moment it settles; you keep every credit of the package for your ads.' };
|
||||
}
|
||||
return { error: (r && r.error) || 'The purchase did not go through. Nothing was taken.' };
|
||||
}
|
||||
|
||||
// a package purchase landing on chain fulfils this account's waiting order (one pass per purchase of $5 or more)
|
||||
async function onEvent(ev) {
|
||||
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
|
||||
const c = cfg(); if ((ev.priceCents || 0) < c.price) return null;
|
||||
const a = (ev.devEmail && !R.isProd) ? { email: ev.devEmail } : await R.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
|
||||
const e = String(a.email).toLowerCase();
|
||||
const p = passes.get(e); if (p && (p.bought || []).some(b => b.tx && b.tx === ev.tx)) return null; // each purchase counts once
|
||||
const w = waitingOrder(e); if (!w) return null;
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents: ev.priceCents, paidAt: Date.now() }));
|
||||
const x = extend(e, 'package', { tx: ev.tx, cents: ev.priceCents, order: w.order }, ev.ts || Date.now());
|
||||
console.log('gamepass fulfilled by package', e, 'tx', String(ev.tx).slice(0, 12), 'until', new Date(x.until).toISOString());
|
||||
return { order: w.order, until: x.until };
|
||||
}
|
||||
|
||||
// ---- the caps ----
|
||||
function capsFor(email, now, game) {
|
||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const day = dayKey(t); const pass = flag(e, t).active;
|
||||
const lim = pass ? c.pass : c.free; const M = L.members[e]; const D = M && M.days[day];
|
||||
const used = { daily: r6(D ? D.daily : 0), total: r6(D ? D.total : 0) };
|
||||
const out = { daily: lim.daily, total: lim.total, used, day, enforced: enforcedOn(c, day), pass };
|
||||
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
|
||||
return out;
|
||||
}
|
||||
|
||||
// POST /api/partner/polgrant. Returns { allowed, deferred, pass, day } (+ carried, capHit, enforced, repeat).
|
||||
function grant(o) {
|
||||
const e = String(o.email || '').toLowerCase(); const game = String(o.game || '').toLowerCase(); const kind = o.kind === 'progress' ? 'progress' : 'daily';
|
||||
const pol = r6(o.pol); const ref = String(o.ref || '').slice(0, 120); const t = o.now || Date.now(); const day = dayKey(t);
|
||||
if (!e || !GAMES.includes(game) || !ref || !(pol >= 0)) return { error: 'memberId/email, game, kind, pol and ref are required' };
|
||||
const key = game + ':' + ref;
|
||||
const prev = L.refs[key];
|
||||
if (prev) return { allowed: prev.allowed, deferred: prev.deferred, pass: prev.pass, day: prev.day, carried: prev.carried || 0, capHit: prev.capHit || null, enforced: !!prev.enforced, repeat: true, voided: !!prev.voided };
|
||||
const c = cfg(); const pass = flag(e, t).active; const lim = pass ? c.pass : c.free; const enforced = enforcedOn(c, day);
|
||||
const M = member(e); const D = dayRow(M, day); const tier = D.tier[pass ? 'pass' : 'free'];
|
||||
let totalRem = Math.max(0, r6(lim.total - D.total)), dailyRem = Math.max(0, r6(lim.daily - D.daily));
|
||||
// carry-forward: progress POL deferred on an EARLIER day for this game is paid first, inside today's total cap
|
||||
let carried = 0; const q = M.deferred[game] || [];
|
||||
for (const d of q) {
|
||||
if (d.day >= day || d.left <= 0) continue;
|
||||
const take = enforced ? Math.min(d.left, Math.max(0, r6(totalRem - carried))) : d.left;
|
||||
if (take <= 0) break;
|
||||
d.left = r6(d.left - take); carried = r6(carried + take); d.paid = (d.paid || []).concat([{ day, pol: take, ref }]).slice(-20);
|
||||
}
|
||||
M.deferred[game] = q.filter(d => d.left > 0);
|
||||
if (carried) { D.total = r6(D.total + carried); D.carried = r6(D.carried + carried); tier.allowed = r6(tier.allowed + carried); totalRem = Math.max(0, r6(totalRem - carried)); }
|
||||
// the new grant
|
||||
let allowed = pol, deferred = 0, dropped = 0, capHit = null;
|
||||
const wouldAllowed = kind === 'daily' ? Math.min(pol, dailyRem, totalRem) : Math.min(pol, totalRem);
|
||||
const wouldHit = wouldAllowed < pol ? (kind === 'daily' && dailyRem <= totalRem ? 'daily' : 'total') : null;
|
||||
if (enforced) {
|
||||
allowed = r6(wouldAllowed); capHit = wouldHit;
|
||||
if (kind === 'daily') { dropped = r6(pol - allowed); if (dropped) D.dropped = r6(D.dropped + dropped); }
|
||||
else { deferred = r6(pol - allowed); if (deferred) { q.push({ ref, pol, left: deferred, ts: t, day }); M.deferred[game] = q; D.deferredOut = r6(D.deferredOut + deferred); } }
|
||||
if (capHit) { D.hits[capHit] += 1; tier[capHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; }
|
||||
} else if (wouldHit) { // before capsStartDate: everything is allowed, but Admin sees what the caps would have done
|
||||
D.would[kind === 'daily' ? 'dropped' : 'deferred'] = r6(D.would[kind === 'daily' ? 'dropped' : 'deferred'] + (pol - wouldAllowed));
|
||||
D.would[wouldHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1;
|
||||
}
|
||||
if (kind === 'daily') D.daily = r6(D.daily + allowed);
|
||||
D.total = r6(D.total + allowed); tier.allowed = r6(tier.allowed + allowed); D.grants += 1;
|
||||
// tournament activity: one point per reported grant (progress and daily weigh the same)
|
||||
if (pol > 0) { const wk = weekKey(t); M.weeks[wk] = M.weeks[wk] || {}; M.weeks[wk][game] = (M.weeks[wk][game] || 0) + 1; }
|
||||
if (capHit) { const p = passes.get(e) || { until: 0, bought: [] }; passes.set(e, Object.assign({}, p, { lastCapHit: { ts: t, day, game, kind: capHit, pass } })); }
|
||||
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed };
|
||||
L.refs[key] = out; touch();
|
||||
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false };
|
||||
}
|
||||
|
||||
// POST /api/partner/polgrant/void: the game decided not to pay after all. Reverses this ref's own share (the carry it triggered
|
||||
// belongs to earlier refs and stays). The ref stays answered, as voided, so a replay is still idempotent.
|
||||
function voidGrant(o) {
|
||||
const game = String(o.game || '').toLowerCase(); const ref = String(o.ref || '').slice(0, 120); const key = game + ':' + ref;
|
||||
const prev = L.refs[key]; if (!prev) return { ok: true, unknown: true };
|
||||
if (prev.voided) return { ok: true, voided: true, repeat: true };
|
||||
const M = member(prev.email); const D = dayRow(M, prev.day);
|
||||
const own = r6(prev.own || 0);
|
||||
D.total = Math.max(0, r6(D.total - own)); if (prev.kind === 'daily') D.daily = Math.max(0, r6(D.daily - own));
|
||||
const tier = D.tier[prev.pass ? 'pass' : 'free']; tier.allowed = Math.max(0, r6(tier.allowed - own));
|
||||
let removed = 0; const q = M.deferred[game] || []; for (const d of q) if (d.ref === ref) { removed = r6(removed + d.left); d.left = 0; } M.deferred[game] = q.filter(d => d.left > 0);
|
||||
if (removed) D.deferredOut = Math.max(0, r6(D.deferredOut - removed));
|
||||
const wk = weekKey(prev.ts || Date.now()); if (M.weeks[wk] && M.weeks[wk][game]) M.weeks[wk][game] -= 1;
|
||||
Object.assign(prev, { voided: true, allowed: 0, deferred: 0, carried: 0, voidedAt: Date.now(), reversed: { allowed: own, deferred: removed } }); touch();
|
||||
return { ok: true, voided: true, reversed: { allowed: own, deferred: removed } };
|
||||
}
|
||||
|
||||
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
|
||||
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
|
||||
function holdersIn(start, end) {
|
||||
const out = [];
|
||||
for (const [e, p] of passes) { if (!p || !(p.until > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
|
||||
return out;
|
||||
}
|
||||
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
|
||||
function salesIn(start, end) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
|
||||
function scoresFor(wk, emails) {
|
||||
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
|
||||
return { email: e, score, games: g, first }; }).filter(x => x.score > 0).sort((a, b) => b.score - a.score || a.first - b.first || (a.email < b.email ? -1 : 1));
|
||||
}
|
||||
async function runTournament(startTs, opts) {
|
||||
const c = cfg(); const start = weekStart(startTs); const end = start + 7 * 86400000; const wk = dayKey(start);
|
||||
if (prizes.get(wk) && !(opts && opts.force)) return prizes.get(wk);
|
||||
const polUsd = await R.polUsd().catch(() => 0);
|
||||
if (!(polUsd > 0)) return { error: 'POL rate unavailable; the tournament for the week of ' + wk + ' will be settled on the next hourly pass.' };
|
||||
const sales = salesIn(start, end); const poolUsd = Math.round(sales.usd * c.pct) / 100;
|
||||
const poolPol = r6(poolUsd / polUsd);
|
||||
const ranked = scoresFor(wk, holdersIn(start, end));
|
||||
const winners = [];
|
||||
for (let i = 0; i < Math.min(3, ranked.length); i++) {
|
||||
const x = ranked[i]; let a = null; try { a = await R.accounts.byEmail(x.email); } catch (e) {}
|
||||
winners.push({ place: i + 1, email: x.email, username: (a && a.username) || null, memberId: (a && a.memberId) || 0, wallet: (a && a.address) || null, score: x.score, games: x.games, pol: r6(poolPol * SHARES[i]), usd: Math.round(poolUsd * SHARES[i] * 100) / 100, status: 'pending', tx: null });
|
||||
}
|
||||
const row = { week: wk, label: 'week of ' + dayLabel(wk), start, end, sales: sales.n, salesUsd: sales.usd, pct: c.pct, poolUsd, polUsd, poolPol, holders: holdersIn(start, end).length, ranked: ranked.length, winners,
|
||||
unallocatedPol: r6(poolPol - winners.reduce((n, w) => n + w.pol, 0)), ranAt: Date.now(), posted: false };
|
||||
prizes.set(wk, row);
|
||||
console.log('gamepass tournament', wk, 'sales', sales.n, 'pool', poolPol, 'POL', 'winners', winners.length);
|
||||
if (winners.length && c.enabled) {
|
||||
const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}'];
|
||||
const lines = winners.map(w => medal[w.place - 1] + ' ' + (w.username ? '@' + w.username : 'member #' + (w.memberId || '?')) + ' · ' + w.score + ' plays · ' + w.pol.toFixed(2) + ' POL');
|
||||
const html = '\u{1F3AE} <b>Game Pass Tournament</b> · ' + row.label + '\n' + lines.join('\n') + '\n' + sales.n + ' pass' + (sales.n === 1 ? '' : 'es') + ' sold · prize pool ' + poolPol.toFixed(2) + ' POL (' + c.pct + '% of pass sales)\n'
|
||||
+ 'Prizes are paid in POL by the games to the winners’ InstantAdPay wallets. Get the Pass: https://instantadpay.com/my#games?pass=1';
|
||||
try { await R.telegram(html); row.posted = true; prizes.set(wk, row); } catch (e) { console.error('gamepass tournament post', e.message); }
|
||||
for (const w of winners) { try { await R.notify(w.email, 'Game Pass Tournament: you placed #' + w.place, '<p>You finished <b>#' + w.place + '</b> in the Game Pass Tournament for the ' + row.label + ' with ' + w.score + ' plays across the games. Your prize of <b>' + w.pol.toFixed(2) + ' POL</b> is paid to the wallet on your InstantAdPay account by the games this week.</p>'); } catch (e) {} }
|
||||
}
|
||||
return row;
|
||||
}
|
||||
// hourly: once Monday 9 AM Central has passed and the closed week has no row yet, exactly one app copy settles it (marks.claim)
|
||||
async function tournamentTick(now) {
|
||||
const t = now || Date.now(); const c = cfg(); if (!c.enabled) return null;
|
||||
const ws = weekStart(t); if (t < ws + 9 * 3600000) return null; // not yet 9 AM Monday for the week that just closed
|
||||
const prev = ws - 7 * 86400000; const wk = dayKey(prev);
|
||||
if (prizes.get(wk)) return null;
|
||||
if (!holdersIn(prev, ws).length && !salesIn(prev, ws).n) { prizes.set(wk, { week: wk, label: 'week of ' + dayLabel(wk), start: prev, end: ws, sales: 0, salesUsd: 0, poolPol: 0, winners: [], ranAt: Date.now(), empty: true }); return null; }
|
||||
if (!(await R.marks.claim('gamepass-tournament:' + wk))) return null;
|
||||
return runTournament(prev);
|
||||
}
|
||||
// GET /api/partner/tournament/pending: prize rows the games still have to pay (the Road Agent faucet pattern)
|
||||
function pending() { const out = []; for (const [, row] of prizes) for (const w of row.winners || []) if (w.status === 'pending') out.push({ week: row.week, label: row.label, place: w.place, email: w.email, username: w.username, memberId: w.memberId, wallet: w.wallet, pol: w.pol, usd: w.usd, score: w.score }); return out.sort((a, b) => a.week < b.week ? -1 : a.week > b.week ? 1 : a.place - b.place); }
|
||||
function markPaid(week, place, tx, by) {
|
||||
const row = prizes.get(String(week)); if (!row) return { error: 'no such week' };
|
||||
const w = (row.winners || []).find(x => x.place === Number(place)); if (!w) return { error: 'no such place' };
|
||||
if (w.status === 'paid') return { ok: true, repeat: true, tx: w.tx };
|
||||
Object.assign(w, { status: 'paid', tx: String(tx || '').slice(0, 80), paidAt: Date.now(), paidBy: by || null }); prizes.set(String(week), row);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// ---- admin ----
|
||||
function adminStats(now) {
|
||||
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
|
||||
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
|
||||
for (const [, p] of passes) { if (!p) continue; if ((p.until || 0) > t) active += 1; for (const b of p.bought || []) { if (!isSale(b)) { comped += 1; continue; } soldTotal += 1; usdTotal += Number(b.usd) || 0; if (b.ts >= ws) { soldWeek += 1; usdWeek += Number(b.usd) || 0; } } }
|
||||
for (const [, o] of orders) if (o.status === 'waiting') waiting += 1;
|
||||
const wk = { pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, carried: 0, dropped: 0, deferredOut: 0, grants: 0, would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 }, players: 0 };
|
||||
const today = { allowed: 0, grants: 0, players: 0 };
|
||||
let qEntries = 0, qPol = 0, qMembers = 0; const byGame = {};
|
||||
for (const [e, M] of Object.entries(L.members)) {
|
||||
let inWeek = false;
|
||||
for (const [d, D] of Object.entries(M.days)) {
|
||||
if (d < wkFrom) continue; inWeek = true;
|
||||
for (const k of ['pass', 'free']) { wk[k].allowed = r6(wk[k].allowed + D.tier[k].allowed); wk[k].hitsDaily += D.tier[k].hitsDaily; wk[k].hitsTotal += D.tier[k].hitsTotal; }
|
||||
wk.carried = r6(wk.carried + D.carried); wk.dropped = r6(wk.dropped + D.dropped); wk.deferredOut = r6(wk.deferredOut + D.deferredOut); wk.grants += D.grants;
|
||||
for (const k of ['dropped', 'deferred']) wk.would[k] = r6(wk.would[k] + D.would[k]); wk.would.hitsDaily += D.would.hitsDaily; wk.would.hitsTotal += D.would.hitsTotal;
|
||||
if (d === day) { today.allowed = r6(today.allowed + D.total); today.grants += D.grants; today.players += 1; }
|
||||
}
|
||||
if (inWeek) wk.players += 1;
|
||||
let mine = 0; for (const [g, q] of Object.entries(M.deferred)) for (const x of q) { qEntries += 1; qPol = r6(qPol + x.left); mine += 1; byGame[g] = r6((byGame[g] || 0) + x.left); }
|
||||
if (mine) qMembers += 1;
|
||||
const W = M.weeks[wkFrom] || {}; for (const [g, n] of Object.entries(W)) { byGame['plays:' + g] = (byGame['plays:' + g] || 0) + n; }
|
||||
void e;
|
||||
}
|
||||
const rows = [...prizes.values()].sort((a, b) => a.week < b.week ? 1 : -1);
|
||||
return { enabled: c.enabled, settings: { price: c.price, days: c.days, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
|
||||
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
|
||||
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting },
|
||||
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
|
||||
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
|
||||
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
|
||||
tournament: { lastRun: rows[0] ? rows[0].ranAt : null, last: rows[0] || null, next: nextTournamentAt(t), pending: pending().length, history: rows.slice(0, 8) } };
|
||||
}
|
||||
|
||||
// ---- housekeeping: answered refs and day rows older than KEEP_DAYS, week tallies older than 10 weeks ----
|
||||
function prune(now) {
|
||||
const t = now || Date.now(); const cut = t - KEEP_DAYS * 86400000; const cutDay = dayKey(cut); const cutWeek = dayKey(weekStart(t - 70 * 86400000)); let n = 0;
|
||||
for (const [k, r] of Object.entries(L.refs)) if ((r.ts || 0) < cut) { delete L.refs[k]; n++; }
|
||||
for (const [e, M] of Object.entries(L.members)) {
|
||||
for (const d of Object.keys(M.days)) if (d < cutDay) { delete M.days[d]; n++; }
|
||||
for (const w of Object.keys(M.weeks)) if (w < cutWeek) { delete M.weeks[w]; n++; }
|
||||
if (!Object.keys(M.days).length && !Object.keys(M.weeks).length && !Object.values(M.deferred).some(q => q.length)) delete L.members[e];
|
||||
}
|
||||
for (const [k, o] of orders) if (o.status === 'waiting' && t - o.ts > 30 * 86400000) orders.delete(k); // a pass order nobody paid for in a month is forgotten
|
||||
if (n) touch();
|
||||
return n;
|
||||
}
|
||||
|
||||
module.exports = { init, cfg, GAMES, NAMES, flag, view, buy, comp, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
||||
_ledger: () => L };
|
||||
+22
-1
@@ -101,6 +101,7 @@
|
||||
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
|
||||
<button data-pane="releases" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg>Releases</button>
|
||||
<button data-pane="pnl" type="button"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg>P&L</button>
|
||||
<button data-pane="gamepass" type="button"><svg viewBox="0 0 24 24"><rect x="2.5" y="7" width="19" height="11" rx="5.5"/><path d="M7 11v3M5.5 12.5h3"/><circle cx="15.5" cy="11.5" r="1.1"/><circle cx="18" cy="13.5" r="1.1"/></svg>Game Pass</button>
|
||||
<button data-pane="settings" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>Settings</button>
|
||||
</nav>
|
||||
<div class="bo-links">
|
||||
@@ -479,6 +480,26 @@
|
||||
<p><button class="btn small sec" type="button" id="burnerRun">Run now</button></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pane" id="pane-gamepass" hidden>
|
||||
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:0" id="gpStats"><p class="small muted">…</p></div>
|
||||
<div class="grid c2" style="margin-top:16px">
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>This week</h3><span class="sub" id="gpWeekSub"></span></div>
|
||||
<div id="gpWeek" class="small">…</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Pass Tournament</h3><span class="sub" id="gpTourSub"></span></div>
|
||||
<div id="gpTour" class="small">…</div>
|
||||
<p style="margin:12px 0 0;display:flex;gap:8px;flex-wrap:wrap"><button class="btn small sec" id="gpTourRun" type="button">Settle last week now</button></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Comp a pass</h3><span class="sub">support: one pass week, recorded as no sale</span></div>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0"><input id="gpCompEmail" placeholder="member email" style="max-width:260px"><input id="gpCompWhy" placeholder="why" style="max-width:220px"><button class="btn small" id="gpComp" type="button">Give one pass week</button></p>
|
||||
</div>
|
||||
<p class="small muted">Settings live in Settings › Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.</p>
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-settings" hidden>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
|
||||
@@ -521,6 +542,6 @@
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/admin.js?v=20261006gm"></script>
|
||||
<script src="/assets/admin.js?v=20261016gp"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+36
-2
@@ -44,8 +44,8 @@
|
||||
});
|
||||
|
||||
// ── panes ──
|
||||
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
|
||||
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
|
||||
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' };
|
||||
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings };
|
||||
function setPane(name) {
|
||||
if (!TITLES[name]) name = 'overview';
|
||||
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
|
||||
@@ -1008,6 +1008,40 @@
|
||||
catch (e) { $('siteErr').textContent = e.message; $('siteErr').hidden = false; }
|
||||
}));
|
||||
|
||||
// ---- Game Pass (2026-10-16): passes sold, active, POL out per pass week, cap hits, deferred queue, tournament ----
|
||||
async function loadGamePass() {
|
||||
const r = await api('/api/admin/gamepass/stats');
|
||||
const pol = n => Number(n || 0).toFixed(2); const usd = n => '$' + Number(n || 0).toFixed(2);
|
||||
const tile = (v, lb, cls, sub) => '<div class="statx' + (cls ? ' ' + cls : '') + '"><div><div class="nv">' + v + '</div><div class="lb">' + lb + '</div>' + (sub ? '<span class="chip flat">' + sub + '</span>' : '') + '</div></div>';
|
||||
const P = r.passes || {}, W = (r.pol && r.pol.week) || {}, H = (r.capHits && r.capHits.week) || { free: {}, pass: {} }, Q = r.deferredQueue || {}, T = r.tournament || {}, S = r.settings || {};
|
||||
$('gpStats').innerHTML = tile(r.enabled ? 'ON' : 'OFF', 'Game Pass', r.enabled ? 'c-cyan' : '', S.enforced ? 'caps enforced' : S.capsStart ? 'caps from ' + S.capsStart : 'caps recorded only')
|
||||
+ tile(P.soldWeek || 0, 'Passes sold this week', 'c-violet', usd(P.usdWeek) + ' · ' + (P.soldTotal || 0) + ' all time')
|
||||
+ tile(P.active || 0, 'Active passes', 'c-cyan', (P.waitingOrders || 0) + ' waiting for a package')
|
||||
+ tile(pol(W.pass), 'POL to pass holders this week', 'c-amber', (P.soldWeek ? pol(W.perPass) + ' per pass sold' : 'no passes sold yet'))
|
||||
+ tile(pol(W.free), 'POL to free players this week', '', (W.players || 0) + ' players · ' + (W.grants || 0) + ' grants')
|
||||
+ tile((H.free.daily || 0) + (H.free.total || 0), 'Free cap hits this week', 'c-amber', (H.free.daily || 0) + ' daily · ' + (H.free.total || 0) + ' total')
|
||||
+ tile((H.pass.daily || 0) + (H.pass.total || 0), 'Pass cap hits this week', '', (H.pass.daily || 0) + ' daily · ' + (H.pass.total || 0) + ' total')
|
||||
+ tile(Q.entries || 0, 'Deferred queue', 'c-violet', pol(Q.pol) + ' POL · ' + (Q.members || 0) + ' members');
|
||||
$('gpWeekSub').textContent = r.week ? r.week.label + ' · today ' + r.week.day : '';
|
||||
const would = (r.capHits && r.capHits.would) || {};
|
||||
$('gpWeek').innerHTML = '<table class="adm-table">'
|
||||
+ '<tr><td>Carried forward (deferred progress paid on a later day)</td><td class="num">' + pol(W.carried) + ' POL</td></tr>'
|
||||
+ '<tr><td>Dropped (daily play over the daily cap)</td><td class="num">' + pol(W.dropped) + ' POL</td></tr>'
|
||||
+ '<tr><td>Deferred out (progress over the total cap, pays later)</td><td class="num">' + pol(W.deferredOut) + ' POL</td></tr>'
|
||||
+ (S.enforced ? '' : '<tr><td colspan="2" class="muted">Before capsStartDate, what the caps WOULD have done: ' + pol(would.dropped) + ' POL dropped, ' + pol(would.deferred) + ' POL deferred, ' + ((would.hitsDaily || 0) + (would.hitsTotal || 0)) + ' cap hits.</td></tr>')
|
||||
+ '<tr><td>Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day)</td><td class="num">' + S.price + ' credits · ' + S.days + ' days</td></tr>'
|
||||
+ '</table>'
|
||||
+ (Q.byGame && Object.keys(Q.byGame).length ? '<p class="muted" style="margin:8px 0 0">By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '</p>' : '');
|
||||
$('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid';
|
||||
const L = T.last;
|
||||
$('gpTour').innerHTML = !L ? '<p class="muted">No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).</p>'
|
||||
: '<p><b>' + esc(L.label) + '</b>: ' + (L.sales || 0) + ' pass' + (L.sales === 1 ? '' : 'es') + ' sold (' + usd(L.salesUsd) + '), pool ' + pol(L.poolPol) + ' POL at $' + Number(L.polUsd || 0).toFixed(4) + ' per POL, ' + (L.holders || 0) + ' holders, ' + (L.ranked || 0) + ' with plays' + (L.posted ? ' · posted to Telegram' : '') + '</p>'
|
||||
+ (L.winners && L.winners.length ? '<table class="adm-table">' + L.winners.map(w => '<tr><td>#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '</td><td>' + w.score + ' plays</td><td class="num">' + pol(w.pol) + ' POL</td><td>' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '</td></tr>').join('') + '</table>' : '<p class="muted">No pass holder reported any plays that week.</p>')
|
||||
+ ((T.history || []).length > 1 ? '<p class="muted" style="margin:8px 0 0">Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '</p>' : '');
|
||||
}
|
||||
$('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); }));
|
||||
$('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value }); IAP.status('Pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); }));
|
||||
|
||||
async function loadSettings() {
|
||||
const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]);
|
||||
ratesObj = r.rates || {}; drawRates();
|
||||
|
||||
+58
-2
@@ -788,6 +788,7 @@
|
||||
earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', games: 'Games',
|
||||
wallet: 'Wallet & account', profile: 'Profile' };
|
||||
function setPane(name) {
|
||||
const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games)
|
||||
if (!PANES.includes(name)) name = 'overview';
|
||||
for (const p of PANES) {
|
||||
const el = $('pane-' + p);
|
||||
@@ -806,7 +807,7 @@
|
||||
if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits
|
||||
if (name === 'training') loadTraining();
|
||||
if (name === 'pipeline') loadPipeline();
|
||||
if (name === 'games') loadGames();
|
||||
if (name === 'games') loadGames(paneQ);
|
||||
document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer
|
||||
if (location.hash !== '#' + name) history.replaceState(null, '', '#' + name);
|
||||
}
|
||||
@@ -1681,6 +1682,60 @@
|
||||
} catch (e) {}
|
||||
}
|
||||
loadWednesdayCard(); setInterval(loadWednesdayCard, 120000);
|
||||
|
||||
// ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ----
|
||||
const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
|
||||
const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, '');
|
||||
async function loadGamePassCard(highlight) {
|
||||
const card = $('gpCard'); if (!card) return;
|
||||
let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {}
|
||||
if (!gp || !gp.enabled) { card.hidden = true; return; }
|
||||
const caps = gp.caps || {}; const price = gp.price || 500;
|
||||
const state = gp.active ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '</span>'
|
||||
: gp.waiting ? '<span class="badge amber">Waiting for a $' + (gp.usd || 5) + ' package</span>' : '<span class="badge">Not active</span>';
|
||||
const capsLine = caps.enforced
|
||||
? 'Today: <b>' + gpPol(caps.used && caps.used.total) + '</b> of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).'
|
||||
: gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.'
|
||||
: 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.';
|
||||
card.hidden = false; card.classList.toggle('gp-hl', !!highlight);
|
||||
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F Game Pass</h3><span class="sub">$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all nine games</span></div>'
|
||||
+ '<p style="margin:0 0 8px">' + state + '</p>'
|
||||
+ '<p>Free play pays real POL every day. The Pass plays <b>more</b>: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly <b>Pass Tournament</b> with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.</p>'
|
||||
+ '<p class="small muted">' + capsLine + '</p>'
|
||||
+ (gp.waiting ? '<p class="small">Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.</p>' : '')
|
||||
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:10px 0 0">'
|
||||
+ (gp.waiting ? '<button class="btn" type="button" id="gpGoBuy">Buy a $' + (gp.usd || 5) + ' package</button>' : '<button class="btn" type="button" id="gpBuy">' + (gp.active ? 'Extend ' + (gp.days || 7) + ' more days' : 'Get the Pass') + ' \u00b7 ' + price + ' credits</button>')
|
||||
+ '<span class="small muted">Paid with purchased credits from your packages (earned credits never buy a pass). Short? A $' + (gp.usd || 5) + ' package starts it the moment it settles.</span></p>';
|
||||
const b = $('gpBuy'); if (b) b.addEventListener('click', async () => {
|
||||
const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + ' for ' + price + ' purchased credits? Higher daily caps across all nine games, the weekly Pass Tournament and the Pass perks start at once.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' });
|
||||
if (!yes) return;
|
||||
b.disabled = true;
|
||||
try {
|
||||
const r = await api('/api/my/gamepass/buy');
|
||||
if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; }
|
||||
IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok');
|
||||
await loadGamePassCard(true);
|
||||
} catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
|
||||
});
|
||||
const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy'));
|
||||
if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} }
|
||||
}
|
||||
// Overview nudge: a game reported this member hit the free cap (polgrant lastCapHit). Shown once a day per browser, never to pass holders.
|
||||
async function loadGpNudge() {
|
||||
const card = $('gpNudge'); if (!card) return;
|
||||
if (cardHidden('gpnudge')) { card.hidden = true; return; }
|
||||
let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {}
|
||||
if (!gp || !gp.enabled || gp.active || !gp.lastCapHit || gp.lastCapHit.pass) { card.hidden = true; return; }
|
||||
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
|
||||
card.hidden = false;
|
||||
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '</h3><span class="sub">free play keeps paying; the Pass plays more</span></div>'
|
||||
+ '<p>Every member earns real POL in the games up to the daily cap. The <b>Game Pass</b> raises the caps across all nine games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with purchased credits), adds the weekly Pass Tournament and a perk in every game.</p>'
|
||||
+ '<button class="btn" type="button" id="gpNudgeGo">See the Game Pass</button>';
|
||||
$('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1'));
|
||||
try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day
|
||||
cardDismiss(card, 'gpnudge');
|
||||
}
|
||||
loadGpNudge();
|
||||
// launch-day surprise (Marty, 2026-09-20): PolHunter appears at siteConfig.launchAt, not a minute before.
|
||||
// The card and the menu entry flip on their own if the dashboard is already open.
|
||||
let phShown = false;
|
||||
@@ -1712,8 +1767,9 @@
|
||||
if (!j || !j.show) { card.hidden = true; return; }
|
||||
card.hidden = false; $('pdPre').hidden = !j.preview; $('pdLine').textContent = j.line || '';
|
||||
}
|
||||
async function loadGames() {
|
||||
async function loadGames(q) {
|
||||
const el = $('gamesGrid'); if (!el) return;
|
||||
loadGamePassCard(/(^|&)pass=1(&|$)/.test(q || '')).catch(() => {});
|
||||
let g = null; try { g = await (await fetch('/api/my/games')).json(); } catch (e) {}
|
||||
const list = (g && g.games) || [];
|
||||
if (!list.length) { el.innerHTML = '<p class="muted small">No games are open yet. Check back soon.</p>'; return; }
|
||||
|
||||
+4
-1
@@ -182,6 +182,7 @@
|
||||
<div class="card" id="phLaunch" hidden></div>
|
||||
<div class="card" id="fdfCard" hidden></div>
|
||||
<div class="card" id="wwCard" hidden></div>
|
||||
<div class="card" id="gpNudge" hidden></div>
|
||||
<div class="card gs" id="gsCard" hidden>
|
||||
<div class="card-head"><h3>Getting started</h3><span class="sub" id="gsSub"></span></div>
|
||||
<div class="gs-steps" id="gsSteps"></div>
|
||||
@@ -1061,6 +1062,7 @@
|
||||
|
||||
<div class="pane" id="pane-games" hidden>
|
||||
<div class="card"><h3>Games</h3><p class="muted small">Games in the InstantAdPay network, the Polygon wing of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>. They pay in POL to the wallet on your InstantAdPay account, and one tap signs you in.</p></div>
|
||||
<div class="card" id="gpCard" hidden></div>
|
||||
<div class="games-grid" id="gamesGrid"><p class="muted small">Loading games…</p></div>
|
||||
<style>.games-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:16px;margin-top:4px}
|
||||
.game-card{background:var(--panel-solid);border:1px solid var(--line-strong);border-radius:var(--radius);overflow:hidden;display:flex;flex-direction:column}
|
||||
@@ -1072,6 +1074,7 @@
|
||||
.game-card .gc-pre{display:inline-block;font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;padding:2px 6px;border-radius:5px;background:#fde68a;color:#7c2d12;margin-left:6px}
|
||||
.game-card .btn{margin-top:auto;text-align:center}
|
||||
.game-card{position:relative}
|
||||
#gpCard.gp-hl{outline:2px solid var(--gold,#e2b04a);outline-offset:2px}
|
||||
.game-card .gc-ribbon{position:absolute;top:10px;right:10px;display:inline-flex;align-items:center;gap:6px;background:#FF5FA2;color:#2b0418;font-weight:700;font-size:11px;letter-spacing:.1em;text-transform:uppercase;padding:5px 10px;border-radius:6px;box-shadow:0 3px 0 #9c2a5d}
|
||||
.game-card .gc-ribbon i{width:7px;height:7px;border-radius:50%;background:#2b0418;display:inline-block;animation:gcPulse 1.4s ease-in-out infinite}
|
||||
@keyframes gcPulse{50%{opacity:.25}}
|
||||
@@ -1156,7 +1159,7 @@
|
||||
<script src="/assets/common.js?v=20261015a"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20261015a"></script>
|
||||
<script src="/assets/my.js?v=20261015a"></script>
|
||||
<script src="/assets/my.js?v=20261016a"></script>
|
||||
<script src="/assets/chat.js?v=20260907l"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
// Game Pass + account-wide POL caps, end to end against a LOCAL copy (2026-10-16, docs/GAME-PASS.md).
|
||||
// node qa/gamepass.mjs (or: bash qa/run.sh gamepass)
|
||||
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB, no mail key, devCode sign-in) and throwaway game
|
||||
// secrets. Nothing touches production. Covers: settings on/off; buy without purchased credits -> waiting order -> a $5 package
|
||||
// fulfils it; buy -> active, buy again -> extended (the charge is stubbed with devPaid, the real ads.gamePurchase(purchasedOnly)
|
||||
// path needs a position with on-chain credits and is the live PolyWarriors mint path); partner auth (bad sig / stale / unknown game);
|
||||
// /api/partner/player pass + caps; polgrant before capsStartDate (allowed, recorded); daily within/over the cap; progress deferral
|
||||
// and carry-forward on the next day (the Central day is faked with devDay); caps account-wide across games; idempotent ref; void;
|
||||
// pass expiry back to free caps; the tournament settle + pending + paid seam; admin stats. Exit code 1 on any failure.
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const PORT = Number(process.env.GP_PORT || 8799);
|
||||
const B = 'http://127.0.0.1:' + PORT;
|
||||
const GK = crypto.randomBytes(24).toString('hex'), HUNT = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
|
||||
const ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-gamepass-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
|
||||
const near = (a, b, tol) => Math.abs(Number(a) - Number(b)) <= (tol || 1e-6);
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL, ADMIN_PASSWORD: ADMIN, GK_SSO_SECRET: GK, HUNT_SSO_SECRET: HUNT, DEV_POL_USD: '0.10' }) });
|
||||
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
|
||||
const cleanup = () => { try { srv.kill(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
|
||||
|
||||
async function api(p, o, headers) {
|
||||
const opts = { method: (o && o.method) || (o && 'data' in o ? 'POST' : 'GET'), headers: Object.assign({ 'Content-Type': 'application/json' }, headers || {}) };
|
||||
if (o && 'data' in o) opts.body = JSON.stringify(o.data);
|
||||
const r = await fetch(B + p, opts); let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, j, headers: r.headers };
|
||||
}
|
||||
const adminH = { Authorization: 'Bearer ' + ADMIN };
|
||||
// a game's signed POST (3a): X-Game-Ts + X-Game-Sig = HMAC(secret, ts + '\n' + rawBody)
|
||||
async function gamePost(p, body, secret, tsOverride) {
|
||||
const raw = JSON.stringify(body); const ts = tsOverride || String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(B + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': sig }, body: raw });
|
||||
let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
|
||||
}
|
||||
// a game's signed GET (3a): sig = HMAC(secret, 'player:' + who + ':' + ts)
|
||||
async function gameGet(p, q, who, secret) {
|
||||
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret).update('player:' + who + ':' + ts).digest('hex');
|
||||
const r = await fetch(B + p + '?' + new URLSearchParams(Object.assign({}, q, { ts, sig })).toString()); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
|
||||
}
|
||||
const grant = (o, secret, tsOverride) => gamePost('/api/partner/polgrant', o, secret || GK, tsOverride);
|
||||
|
||||
try {
|
||||
for (let i = 0; i < 40; i++) { try { if ((await fetch(B + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
|
||||
async function signIn(email, username) {
|
||||
const s = await api('/api/auth/email/start', { data: { email, fts: Date.now() - 5000 } });
|
||||
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
|
||||
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
|
||||
if (username) await api('/api/my/profile', { data: { username } }, { Cookie: cookie });
|
||||
return { Cookie: cookie };
|
||||
}
|
||||
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10 } }, adminH);
|
||||
const A = 'qa-gp-a@example.com', Bm = 'qa-gp-b@example.com', C = 'qa-gp-c@example.com';
|
||||
const hA = await signIn(A, 'qagpa'), hB = await signIn(Bm, 'qagpb'), hC = await signIn(C, 'qagpc');
|
||||
|
||||
// 1. settings: off by default, member GET says so, buy refused
|
||||
let g = (await api('/api/my/gamepass', null, hA)).j;
|
||||
ok(g && g.enabled === false && g.active === false && g.price === 500 && g.days === 7, 'GET /api/my/gamepass with the pass OFF: enabled false, price 500, days 7', JSON.stringify(g));
|
||||
let r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
||||
ok(r.status === 400 && /not open/.test(r.j && r.j.error || ''), 'buy refused while the pass is off', JSON.stringify(r.j));
|
||||
await api('/api/admin/site', { method: 'PATCH', data: { gamePassEnabled: '1', capsStartDate: '' } }, adminH);
|
||||
g = (await api('/api/my/gamepass', null, hA)).j;
|
||||
ok(g && g.enabled === true && g.caps && g.caps.enforced === false && g.caps.daily === 0.3 && g.caps.total === 2, 'pass ON: GET shows free caps 0.30 / 2 and enforced false (no capsStartDate)', JSON.stringify(g.caps));
|
||||
|
||||
// 2. buy without purchased credits -> waiting order; a $5 package fulfils it
|
||||
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
||||
ok(r.status === 200 && r.j && r.j.needPay === true && r.j.payUrl === '/my?from=gamepass#buy' && r.j.order, 'buy with no purchased credits -> needPay + payUrl + waiting order', JSON.stringify(r.j && { needPay: r.j.needPay, payUrl: r.j.payUrl, need: r.j.need }));
|
||||
const order1 = r.j && r.j.order;
|
||||
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
||||
ok(r.j && r.j.order === order1, 'a second buy attempt reuses the same waiting order', r.j && r.j.order);
|
||||
g = (await api('/api/my/gamepass', null, hA)).j; ok(g.waiting === true && g.active === false, 'GET shows waiting: true', '');
|
||||
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
|
||||
ok(r.j && r.j.order && r.j.order.order === order1, 'a $5 package purchase event fulfils the waiting order', JSON.stringify(r.j));
|
||||
g = (await api('/api/my/gamepass', null, hA)).j; const until1 = g.until;
|
||||
ok(g.active === true && g.waiting === false && near(g.until, Date.now() + 7 * 86400000, 60000) && g.bought === 1, 'pass active for 7 days, waiting cleared', new Date(g.until).toISOString());
|
||||
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
|
||||
ok(r.j && r.j.order === null, 'another package with no waiting order does nothing', JSON.stringify(r.j));
|
||||
// 3. buy while active -> extends from the current until (charge stubbed: devPaid, local only)
|
||||
r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hA);
|
||||
ok(r.status === 200 && r.j.ok && near(r.j.until, until1 + 7 * 86400000, 1000) && r.j.paid === 'credits', 'buy while active extends by 7 days from the current until', new Date(r.j.until).toISOString());
|
||||
r = await api('/api/my/gamepass/buy', { data: { devPaid: true, devDay: '2026-10-20' } }, hB);
|
||||
ok(r.status === 200 && r.j.ok && r.j.active === true, 'member B: buy -> active (sale stamped in the week of Oct 19 for the tournament)', '');
|
||||
|
||||
// 4. partner auth + /api/partner/player
|
||||
let pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: A }, A, GK);
|
||||
ok(pl.status === 200 && pl.j.pass && pl.j.pass.active === true && pl.j.pass.until === until1 + 7 * 86400000 && pl.j.caps.daily === 1.5 && pl.j.caps.total === 5 && pl.j.caps.used.total === 0 && /^\d{4}-\d{2}-\d{2}$/.test(pl.j.caps.day), 'player (pass holder): pass.active, pass caps 1.50 / 5, used 0, Central day', JSON.stringify(pl.j.pass) + ' ' + JSON.stringify(pl.j.caps));
|
||||
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C }, C, GK);
|
||||
ok(pl.status === 200 && pl.j.pass.active === false && pl.j.pass.until === null && pl.j.caps.daily === 0.3 && pl.j.caps.total === 2, 'player (free): pass false, free caps 0.30 / 2', JSON.stringify(pl.j.caps));
|
||||
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C }, C, HUNT);
|
||||
ok(pl.status === 401, 'player signed with another game’s secret -> 401', String(pl.status));
|
||||
pl = await gameGet('/api/partner/player', { game: 'nosuchgame', m: 0, e: C }, C, GK);
|
||||
ok(pl.status === 400, 'unknown game -> 400', String(pl.status));
|
||||
pl = await gameGet('/api/partner/player', { game: 'spellwheel', m: 0, e: C }, C, GK);
|
||||
ok(pl.status === 503, 'a game with no secret configured -> 503', String(pl.status));
|
||||
let gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'auth-stale' }, GK, String(Date.now() - 20 * 60000));
|
||||
ok(gr.status === 401 && /stale/.test(gr.j.error), 'polgrant with a 20-minute-old timestamp -> 401 stale', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'auth-bad' }, HUNT);
|
||||
ok(gr.status === 401, 'polgrant signed with the wrong secret -> 401', String(gr.status));
|
||||
gr = await grant({ memberId: 0, email: 'nobody-here@example.com', game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'x' });
|
||||
ok(gr.status === 404, 'polgrant for an unknown member -> 404', String(gr.status));
|
||||
|
||||
// 5. before capsStartDate: everything allowed, nothing deferred, usage recorded
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'pre:1', devDay: '2026-10-19' });
|
||||
ok(gr.status === 200 && gr.j.allowed === 1 && gr.j.deferred === 0 && gr.j.pass === false && gr.j.enforced === false && gr.j.day === '2026-10-19', 'before capsStartDate: daily 1.0 -> allowed 1.0 (over the 0.30 free cap), enforced false', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 5, ref: 'pre:boss', devDay: '2026-10-19' });
|
||||
ok(gr.j.allowed === 5 && gr.j.deferred === 0, 'before capsStartDate: progress 5 -> allowed 5, nothing deferred', JSON.stringify(gr.j));
|
||||
let st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
|
||||
ok(st && st.enabled === true && st.settings.enforced === false, 'admin stats: enabled, caps not enforced', JSON.stringify(st.settings));
|
||||
|
||||
// 6. enforced: daily within / over the cap, idempotent ref, progress deferral
|
||||
await api('/api/admin/site', { method: 'PATCH', data: { capsStartDate: '2026-10-20' } }, adminH);
|
||||
const D1 = '2026-10-20', D2 = '2026-10-21', D3 = '2026-10-22';
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f1', devDay: D1 });
|
||||
ok(gr.j.allowed === 0.2 && gr.j.deferred === 0 && gr.j.enforced === true && gr.j.capHit === null, 'D1 daily 0.2 -> allowed 0.2', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f2', devDay: D1 });
|
||||
ok(gr.j.allowed === 0.1 && gr.j.deferred === 0 && gr.j.capHit === 'daily', 'D1 daily 0.2 -> allowed 0.1 (daily cap 0.30), the rest dropped, capHit daily', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'f3', devDay: D1 });
|
||||
ok(gr.j.allowed === 0 && gr.j.deferred === 0 && gr.j.capHit === 'daily', 'D1 daily 0.1 at the cap -> allowed 0, nothing deferred', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f2', devDay: D2 });
|
||||
ok(gr.j.allowed === 0.1 && gr.j.repeat === true && gr.j.day === D1, 'same ref f2 again (even on another day) -> the same answer, nothing re-applied', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 5, ref: 'boss:1', devDay: D1 });
|
||||
ok(gr.j.allowed === 1.7 && gr.j.deferred === 3.3 && gr.j.capHit === 'total', 'D1 progress 5 -> allowed 1.7 (total cap 2 minus 0.3 daily), 3.3 deferred', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.5, ref: 'stage:2', devDay: D1 });
|
||||
ok(gr.j.allowed === 0 && gr.j.deferred === 0.5, 'D1 progress 0.5 with the total cap used -> all 0.5 deferred', JSON.stringify(gr.j));
|
||||
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D1 }, C, GK);
|
||||
ok(pl.j.caps.used.daily === 0.3 && pl.j.caps.used.total === 2 && pl.j.caps.pending === 3.8 && pl.j.caps.enforced === true, 'player caps on D1: used 0.30 / 2.0, 3.8 POL pending for Gem Kingdom', JSON.stringify(pl.j.caps));
|
||||
// 7. carry-forward on the next day, inside the total cap, before the new grant
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'f4', devDay: D2 });
|
||||
ok(gr.j.allowed === 2 && gr.j.carried === 2 && gr.j.deferred === 0 && gr.j.capHit === 'total' && gr.j.day === D2, 'D2 daily 0.1 -> allowed 2.0 (2.0 carried from the boss fills the day), the 0.1 dropped', JSON.stringify(gr.j));
|
||||
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D2 }, C, GK);
|
||||
ok(pl.j.caps.used.total === 2 && pl.j.caps.used.daily === 0 && pl.j.caps.pending === 1.8, 'D2 caps: total 2.0 used (all carried), 1.8 still pending', JSON.stringify(pl.j.caps));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.3, ref: 'stage:3', devDay: D3 });
|
||||
ok(gr.j.allowed === 2 && gr.j.carried === 1.8 && gr.j.deferred === 0.1, 'D3 progress 0.3 -> 1.8 carried + 0.2 own = 2.0 allowed, 0.1 deferred', JSON.stringify(gr.j));
|
||||
// account-wide: another game on the same day sees the cap used
|
||||
gr = await grant({ memberId: 0, email: C, game: 'polhunter', kind: 'daily', pol: 0.3, ref: 'find:1', devDay: D3 }, HUNT);
|
||||
ok(gr.j.allowed === 0 && gr.j.capHit === 'total', 'D3 PolHunter daily 0.3 -> allowed 0: the cap is account-wide across games', JSON.stringify(gr.j));
|
||||
// 8. void: this ref's own share is reversed, the carry it triggered stays; a replay stays voided
|
||||
let vd = await gamePost('/api/partner/polgrant/void', { memberId: 0, email: C, game: 'gemkingdom', ref: 'stage:3' }, GK);
|
||||
ok(vd.status === 200 && vd.j.voided === true && vd.j.reversed.allowed === 0.2 && vd.j.reversed.deferred === 0.1, 'void stage:3 -> reversed 0.2 allowed + 0.1 deferred', JSON.stringify(vd.j));
|
||||
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D3 }, C, GK);
|
||||
ok(pl.j.caps.used.total === 1.8 && pl.j.caps.pending === 0, 'D3 caps after the void: 1.8 used (the carry stays), nothing pending', JSON.stringify(pl.j.caps));
|
||||
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.3, ref: 'stage:3', devDay: D3 });
|
||||
ok(gr.j.allowed === 0 && gr.j.repeat === true && gr.j.voided === true, 'replaying a voided ref -> allowed 0, voided', JSON.stringify(gr.j));
|
||||
vd = await gamePost('/api/partner/polgrant/void', { memberId: 0, email: C, game: 'gemkingdom', ref: 'never-granted' }, GK);
|
||||
ok(vd.j.ok === true && vd.j.unknown === true, 'voiding an unknown ref is harmless', JSON.stringify(vd.j));
|
||||
// the Overview nudge source: the free player's last cap hit
|
||||
g = (await api('/api/my/gamepass', null, hC)).j;
|
||||
ok(g.lastCapHit && g.lastCapHit.game === 'polhunter' && g.lastCapHit.kind === 'total' && g.lastCapHit.pass === false, 'member GET carries lastCapHit for the Overview nudge', JSON.stringify(g.lastCapHit));
|
||||
|
||||
// 9. a pass holder gets the pass caps; after expiry the free caps are back
|
||||
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:f1', devDay: D1 });
|
||||
ok(gr.j.allowed === 1 && gr.j.pass === true && gr.j.capHit === null, 'pass holder: daily 1.0 -> allowed 1.0 (pass daily cap 1.50)', JSON.stringify(gr.j));
|
||||
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:f2', devDay: D1 });
|
||||
ok(gr.j.allowed === 0.5 && gr.j.capHit === 'daily', 'pass holder: second daily 1.0 -> allowed 0.5 (1.50 reached)', JSON.stringify(gr.j));
|
||||
g = (await api('/api/my/gamepass?devDay=2026-12-01', null, hA)).j;
|
||||
ok(g.active === false && g.caps.daily === 0.3, 'after expiry (faked Dec 1): active false, free caps', JSON.stringify(g.caps));
|
||||
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:dec', devDay: '2026-12-01' });
|
||||
ok(gr.j.allowed === 0.3 && gr.j.pass === false, 'after expiry: daily 1.0 -> allowed 0.30, pass false', JSON.stringify(gr.j));
|
||||
|
||||
// 10. tournament: the week of Oct 19 (A played, B bought); 5% of $5 = $0.25 at $0.10/POL = 2.5 POL pool, 50% to #1
|
||||
let t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
|
||||
ok(t.status === 200 && t.j.week === '2026-10-19' && t.j.sales === 1 && near(t.j.poolPol, 2.5) && t.j.winners.length === 1 && t.j.winners[0].email === A && near(t.j.winners[0].pol, 1.25) && t.j.winners[0].score === 2, 'tournament week of Oct 19: 1 sale, pool 2.5 POL, A wins #1 with 2 plays -> 1.25 POL pending', JSON.stringify(t.j && { week: t.j.week, sales: t.j.sales, poolPol: t.j.poolPol, winners: t.j.winners.map(w => [w.email, w.score, w.pol, w.status]) }));
|
||||
t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
|
||||
ok(t.j.winners && t.j.winners.length === 1 && t.j.ranAt, 'running the same week again returns the recorded row (no double prizes)', '');
|
||||
let pend = await api('/api/partner/tournament/pending', null, adminH);
|
||||
ok(pend.j.ok && pend.j.pending.length === 1 && pend.j.pending[0].place === 1 && near(pend.j.pending[0].pol, 1.25), 'GET /api/partner/tournament/pending (admin) lists the unpaid prize', JSON.stringify(pend.j.pending));
|
||||
pend = await gameGet('/api/partner/tournament/pending', { game: 'gemkingdom' }, 'tournament', GK);
|
||||
ok(pend.status === 200 && pend.j.pending.length === 1 && pend.j.pending[0].email === A, 'a game can read the pending prizes with its signature', '');
|
||||
let paid = await gamePost('/api/partner/tournament/paid', { game: 'gemkingdom', week: '2026-10-19', place: 1, tx: '0xabc123' }, GK);
|
||||
ok(paid.j.ok === true, 'a game marks the prize paid', JSON.stringify(paid.j));
|
||||
pend = await api('/api/partner/tournament/pending', null, adminH);
|
||||
ok(pend.j.pending.length === 0, 'pending is empty after the payout', '');
|
||||
const inbox = (await api('/api/my/messages', null, hA)).j;
|
||||
const stored = (() => { try { return JSON.parse(fs.readFileSync(path.join(DATA, 'sponsor-messages.json'), 'utf8')).items || []; } catch (e) { return []; } })().find(i => /Game Pass Tournament/.test(i.subject || ''));
|
||||
ok(inbox && JSON.stringify(inbox).includes('Game Pass Tournament') && stored && stored.kind === 'notice', 'the winner got an inbox message of kind notice (never a broadcast pop-up)', stored ? 'kind=' + stored.kind : 'not stored');
|
||||
|
||||
// 11. admin stats + comp
|
||||
st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
|
||||
ok(st.passes.soldTotal === 3 && st.passes.active >= 2 && st.deferredQueue.entries === 0 && st.tournament.last && st.tournament.last.week === '2026-10-19' && typeof st.capHits.week.free.daily === 'number', 'admin stats: 3 passes sold, active >= 2, tournament recorded', JSON.stringify({ passes: st.passes, q: st.deferredQueue, hits: st.capHits.week }));
|
||||
r = await api('/api/admin/gamepass/comp', { data: { email: C, why: 'qa' } }, adminH);
|
||||
g = (await api('/api/my/gamepass', null, hC)).j;
|
||||
ok(r.j.ok && g.active === true && g.caps.daily === 1.5, 'admin comp gives C a pass week: caps now 1.50 / 5', JSON.stringify(g.caps));
|
||||
st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
|
||||
ok(st.passes.soldTotal === 3 && st.passes.usdTotal === 15 && st.passes.comped === 1 && st.passes.active === 3, 'a comp is not a sale (soldTotal 3, $15, comped 1, active 3)', JSON.stringify(st.passes));
|
||||
|
||||
// 12. the hand-off token carries the flag
|
||||
const gkO = { Origin: 'https://gemkingdom.app' }; // the game's own origin, as its sign-in page sends it
|
||||
const hv = await api('/api/game/auth/start', { data: { email: A, game: 'gemkingdom', fts: Date.now() - 5000 } }, gkO);
|
||||
const vv = await api('/api/game/auth/verify', { data: { email: A, game: 'gemkingdom', code: hv.j && hv.j.devCode } }, gkO);
|
||||
if (!(vv.j && vv.j.token)) console.log(' game auth answer:', JSON.stringify(hv.j), JSON.stringify(vv.j));
|
||||
const tokenClaims = vv.j && vv.j.token ? JSON.parse(Buffer.from(String(vv.j.token).split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')) : null;
|
||||
ok(tokenClaims && tokenClaims.gamePass && tokenClaims.gamePass.active === true && tokenClaims.gamePass.until === until1 + 7 * 86400000, 'in-game sign-in token carries gamePass { active, until }', JSON.stringify(tokenClaims && tokenClaims.gamePass));
|
||||
|
||||
// the ledger file on the volume (saves are debounced 500 ms)
|
||||
await sleep(1200);
|
||||
ok(fs.existsSync(path.join(DATA, 'gamepass-ledger.json')), 'cap ledger persisted to DATA_DIR/gamepass-ledger.json', fs.readdirSync(DATA).join(','));
|
||||
const ot = JSON.parse(fs.readFileSync(path.join(DATA, 'open-tokens.json'), 'utf8'));
|
||||
ok(ot.gamepass && ot.gamepass[A] && ot.gporders && ot.gpprizes && ot.gpprizes['2026-10-19'], 'pass store, orders and prizes persisted in the durable open-tokens store', Object.keys(ot).join(','));
|
||||
} catch (e) {
|
||||
console.error('FAIL harness error', e && e.stack || e); fails++;
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
if (fails && /gamepass/i.test(srvLog)) console.log('--- server log (gamepass lines) ---\n' + srvLog.split('\n').filter(l => /gamepass|Error|error/.test(l)).slice(-30).join('\n'));
|
||||
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
|
||||
process.exit(fails ? 1 : 0);
|
||||
@@ -5,6 +5,7 @@
|
||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
|
||||
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
||||
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
|
||||
set -u
|
||||
@@ -33,6 +34,8 @@ elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
elif [ "$MODE" = "door" ]; then
|
||||
node qa/door.mjs || status=1
|
||||
elif [ "$MODE" = "gamepass" ]; then
|
||||
node qa/gamepass.mjs || status=1
|
||||
elif [ "$MODE" = "earn" ]; then
|
||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
|
||||
else
|
||||
|
||||
+11
-1
@@ -115,6 +115,16 @@ if (MODE === 'member' || MODE === 'all') {
|
||||
await page.screenshot({ path: OUT + '/my-' + pn + '.png' }).catch(() => {});
|
||||
console.log('ok', label, 'subtabs:', subs.length);
|
||||
}
|
||||
// Game Pass card on the Games tab (2026-10-16): hidden while gamePassEnabled is off, rendered with its state and Buy button once on; /my#games?pass=1 highlights it
|
||||
await page.request.patch(LOCAL + '/api/admin/site', { headers: { Authorization: 'Bearer ' + (process.env.ADMIN_PASSWORD || 'localtest'), 'Content-Type': 'application/json' }, data: { gamePassEnabled: '1' } }).catch(() => {});
|
||||
await page.goto(LOCAL + '/my#games?pass=1', { waitUntil: 'networkidle' }); await page.waitForTimeout(1500); await hide(page);
|
||||
const gpVis = await page.evaluate(() => { const c = document.getElementById('gpCard'); return !!(c && !c.hidden && c.offsetHeight > 40 && /Game Pass/.test(c.textContent) && c.querySelector('#gpBuy, #gpGoBuy')); });
|
||||
if (!gpVis) note('bug', L + 'my#games/gamepass', 'Game Pass card did not render with gamePassEnabled on (deep link /my#games?pass=1)');
|
||||
else { await domChecks(page, L + 'my#games/gamepass'); console.log('ok Game Pass card'); }
|
||||
await page.request.patch(LOCAL + '/api/admin/site', { headers: { Authorization: 'Bearer ' + (process.env.ADMIN_PASSWORD || 'localtest'), 'Content-Type': 'application/json' }, data: { gamePassEnabled: '0' } }).catch(() => {});
|
||||
await page.goto(LOCAL + '/my#games'); await page.reload({ waitUntil: 'load' }); await page.waitForTimeout(2500); await hide(page); // a hash-only goto would not reload the card
|
||||
if (await page.evaluate(() => { const c = document.getElementById('gpCard'); return !!(c && !c.hidden); })) note('bug', L + 'my#games/gamepass', 'Game Pass card shows while gamePassEnabled is off');
|
||||
flush(bag, L + 'my#games/gamepass');
|
||||
await page.click('.bo-menu [data-pane="promo"]'); await page.waitForTimeout(800);
|
||||
if (!(await page.$$('#promoPosts .promo-block')).length) note('bug', L + 'promo', 'no post cards rendered');
|
||||
// viral links: the builder renders a ?ref= link; any page + ?ref=<member> redirects clean and sets the sponsor cookie; an unknown ref sets nothing
|
||||
@@ -144,7 +154,7 @@ if (MODE === 'member' || MODE === 'all') {
|
||||
// admin
|
||||
await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' });
|
||||
await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200);
|
||||
for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'settings']) {
|
||||
for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'settings']) {
|
||||
const label = L + 'admin#' + pn;
|
||||
await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200);
|
||||
const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn);
|
||||
|
||||
@@ -45,6 +45,7 @@ const lssync = require('./lssync');
|
||||
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
|
||||
const gamestats = require('./gamestats');
|
||||
const marks = require('./marks');
|
||||
const gamepass = require('./gamepass'); // the $5 weekly Game Pass + the account-wide POL cap service the games call (2026-10-16)
|
||||
const feedgroup = require('./feedgroup'); // one proof-feed message per purchase: buyer, package, then the tier payouts // one-time claims shared across running instances (deploy overlap) // Google Safe Browsing screen on advertiser destinations
|
||||
const updates = require('./updates');
|
||||
const audit = require('./audit'); // counter audit: views vs delivery logs, charges vs shows (Marty, 2026-09-15) // member update emails from Admin > Releases (Marty, 2026-09-14)
|
||||
@@ -130,7 +131,7 @@ function loadOpenTokens() {
|
||||
const cutoff = Date.now() - 2 * 3600 * 1000; let n = 0;
|
||||
// durable maps are balances and orders, not short-lived tokens: restore every entry whatever its age. Before 2026-10-10 the
|
||||
// age filter silently dropped every PolyWarriors mint pass (no ts on the record) on each deploy; Orlando lost his.
|
||||
const DURABLE = new Set(['pwpasses', 'pwprizes', 'pworders', 'gkorders', 'sdorders']);
|
||||
const DURABLE = new Set(['pwpasses', 'pwprizes', 'pworders', 'gkorders', 'sdorders', 'gamepass', 'gporders', 'gpprizes']);
|
||||
for (const [name, m] of Object.entries(persistedMaps)) {
|
||||
for (const [k, v] of Object.entries(saved[name] || {})) if (v && (DURABLE.has(name) || Number(v.ts || 0) > cutoff)) { Map.prototype.set.call(m, k, v); n++; }
|
||||
}
|
||||
@@ -510,6 +511,7 @@ async function boot() {
|
||||
friday.onEvent(ev).catch(e => console.error('friday bonus', e.message));
|
||||
starter.onEvent(ev).catch(e => console.error('starter bonus', e.message));
|
||||
pwMintOnEvent(ev).catch(e => console.error('polywarriors mint', e.message));
|
||||
gamepass.onEvent(ev).catch(e => console.error('gamepass order', e.message));
|
||||
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
|
||||
sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message));
|
||||
}).catch(e => console.error('marks claim', e.message));
|
||||
@@ -579,7 +581,13 @@ async function boot() {
|
||||
promos.init({ dataDir: DATA_DIR });
|
||||
blog.init({ dataDir: DATA_DIR });
|
||||
adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR });
|
||||
gamepass.init({ dataDir: DATA_DIR, siteConfig, accounts, marks, isProd: IS_PROD, persistedMap, polUsd: polUsdLive,
|
||||
telegram: async html => { const sc = siteConfig(); const chat = String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return false; await telegramSend(chat, html, sc.telegramGamesTopicId || null); return true; },
|
||||
notify: (to, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice') }); // before loadOpenTokens: its maps must exist to be restored
|
||||
loadOpenTokens();
|
||||
setTimeout(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 120 * 1000);
|
||||
setInterval(() => gamepass.tournamentTick().catch(e => console.error('gamepass tournament', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => { try { gamepass.prune(); } catch (e) { console.error('gamepass prune', e.message); } }, 6 * 3600 * 1000).unref();
|
||||
syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR });
|
||||
releases.init({ dataDir: DATA_DIR });
|
||||
ledger.init({ dataDir: DATA_DIR });
|
||||
@@ -643,6 +651,28 @@ async function boot() {
|
||||
}
|
||||
}
|
||||
|
||||
// Game Pass partner helpers (2026-10-16): which secret signs for which game, signature compare, member resolution, dev clock
|
||||
const GP_SECRETS = () => ({ polhunter: String(process.env.HUNT_SSO_SECRET || '').trim(), gemkingdom: GK_SECRET(), spellwheel: SW_SECRET(), spookydoors: SD_SECRET(), polywarriors: PW_SECRET(),
|
||||
clutterhunt: SEEK_SECRET(), polybreak: PB_SECRET(), driprunner: DR_SECRET(), roadagent: RA_SECRET() });
|
||||
function gpPartnerCheck(game) { if (!gamepass.GAMES.includes(game)) return { error: 'unknown game', code: 400 }; const secret = GP_SECRETS()[game] || ''; if (secret.length < 32) return { error: game + ' is not connected', code: 503 }; return { secret }; }
|
||||
const gpSigOk = (want, got) => typeof got === 'string' && want.length === got.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got));
|
||||
async function gpResolve(memberId, email) { // the account behind a game's player: main member id, a linked position's id, or (no wallet yet) the email
|
||||
const id = Number(memberId) || 0; let a = null;
|
||||
if (id) { a = await accounts.byMemberId(id); if (!a) { const pos = await accounts.positionByMember(id); if (pos && pos.email) a = await accounts.byEmail(pos.email); } }
|
||||
if (!a && email && /^[^\s@]+@[^\s@]+$/.test(String(email))) a = await accounts.byEmail(String(email).trim().toLowerCase());
|
||||
return a && a.email ? { email: String(a.email).toLowerCase(), memberId: a.memberId || id || 0, acct: a } : null;
|
||||
}
|
||||
const gpDevNow = devDay => (!IS_PROD && /^\d{4}-\d{2}-\d{2}$/.test(String(devDay || ''))) ? Date.parse(devDay + 'T17:00:00Z') : Date.now(); // local tests fake the Central day
|
||||
// live USD per POL from the catalog quotes (the rate the games use for the tournament pool); cached 10 minutes
|
||||
const polUsdCache = { at: 0, v: 0 };
|
||||
async function polUsdLive() {
|
||||
if (!IS_PROD && Number(process.env.DEV_POL_USD) > 0) return Number(process.env.DEV_POL_USD); // local tests: no RPC
|
||||
if (polUsdCache.at && Date.now() - polUsdCache.at < 600000 && polUsdCache.v > 0) return polUsdCache.v;
|
||||
const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (!pk) return polUsdCache.v || 0;
|
||||
const v = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); if (v > 0) { polUsdCache.v = v; polUsdCache.at = Date.now(); } return v;
|
||||
}
|
||||
// the Game Pass flag rides in every sign-in hand-off token (3a: games get it at sign-in and on every polgrant answer)
|
||||
const gpClaim = c => (c && c.email && (!c.kind || c.kind === 'sso')) ? { gamePass: gamepass.flag(c.email) } : {};
|
||||
function siteConfig() {
|
||||
let saved = {};
|
||||
try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {}
|
||||
@@ -671,6 +701,9 @@ function siteConfig() {
|
||||
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
|
||||
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
|
||||
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
|
||||
// Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records
|
||||
gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5,
|
||||
telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat)
|
||||
pnlFixedMonthlyUsd: 0
|
||||
}, saved);
|
||||
}
|
||||
@@ -1307,7 +1340,7 @@ const DR_SECRET = () => String(process.env.DR_SSO_SECRET || '').trim();
|
||||
const DR_URL = () => String(process.env.DR_URL || 'https://driprunner.saasy.top').replace(/\/+$/, '');
|
||||
const drB64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const drSign = payload => drB64u(crypto.createHmac('sha256', DR_SECRET()).update(payload).digest());
|
||||
function drMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + drSign(payload); }
|
||||
function drMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + drSign(payload); }
|
||||
function drOpen(token) {
|
||||
if (DR_SECRET().length < 32) return { error: 'Drip Runner is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -1333,7 +1366,7 @@ async function drCallback(body) {
|
||||
const GK_SECRET = () => String(process.env.GK_SSO_SECRET || '').trim();
|
||||
const GK_URL = () => String(process.env.GK_URL || 'https://gemkingdom.app').replace(/\/+$/, '');
|
||||
const gkSign = p => drB64u(crypto.createHmac('sha256', GK_SECRET()).update(p).digest());
|
||||
function gkMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + gkSign(payload); }
|
||||
function gkMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gkSign(payload); }
|
||||
function gkOpen(token) {
|
||||
if (GK_SECRET().length < 32) return { error: 'Gem Kingdom is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -1363,7 +1396,7 @@ const SEEK_SECRET = () => String(process.env.SEEK_SSO_SECRET || '').trim();
|
||||
const SEEK_URL = () => String(process.env.SEEK_URL || 'https://clutterhunt.com').replace(/\/+$/, '');
|
||||
const SEEK_ALT = () => String(process.env.SEEK_ALT_URLS || 'https://www.clutterhunt.com,https://clutterhunt.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
|
||||
const seekSign = p => drB64u(crypto.createHmac('sha256', SEEK_SECRET()).update(p).digest());
|
||||
function seekMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + seekSign(payload); }
|
||||
function seekMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + seekSign(payload); }
|
||||
function seekOpen(token) {
|
||||
if (SEEK_SECRET().length < 32) return { error: 'ClutterHunt is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -1383,7 +1416,7 @@ const SW_SECRET = () => String(process.env.SW_SSO_SECRET || '').trim();
|
||||
const SW_URL = () => String(process.env.SW_URL || 'https://spellwheel.com').replace(/\/+$/, '');
|
||||
const SW_ALT = () => String(process.env.SW_ALT_URLS || 'https://www.spellwheel.com,https://spellwheel.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
|
||||
const swSign = p => drB64u(crypto.createHmac('sha256', SW_SECRET()).update(p).digest());
|
||||
function swMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + swSign(payload); }
|
||||
function swMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + swSign(payload); }
|
||||
function swOpen(token) {
|
||||
if (SW_SECRET().length < 32) return { error: 'SpellWheel is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -1399,7 +1432,7 @@ const PB_SECRET = () => String(process.env.PB_SSO_SECRET || '').trim();
|
||||
const PB_URL = () => String(process.env.PB_URL || 'https://polybreak.app').replace(/\/+$/, '');
|
||||
const PB_ALT = () => String(process.env.PB_ALT_URLS || 'https://www.polybreak.app,https://polybreak.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
|
||||
const pbSign = p => drB64u(crypto.createHmac('sha256', PB_SECRET()).update(p).digest());
|
||||
function pbMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + pbSign(payload); }
|
||||
function pbMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pbSign(payload); }
|
||||
function pbOpen(token) {
|
||||
if (PB_SECRET().length < 32) return { error: 'PolyBreak is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -1419,7 +1452,7 @@ const PW_SECRET = () => String(process.env.PW_SSO_SECRET || '').trim();
|
||||
const PW_URL = () => String(process.env.PW_URL || 'https://polywarriors.com').replace(/\/+$/, '');
|
||||
const PW_ALT = () => String(process.env.PW_ALT_URLS || 'https://www.polywarriors.com,https://polywarriors.saasy.top').split(',').map(x => x.trim().replace(/\/+$/, '')).filter(Boolean);
|
||||
const pwSign = p => drB64u(crypto.createHmac('sha256', PW_SECRET()).update(p).digest());
|
||||
function pwMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + pwSign(payload); }
|
||||
function pwMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + pwSign(payload); }
|
||||
async function swCallback(cbUrl, receipt) {
|
||||
if (!swIsGameUrl(cbUrl)) return false;
|
||||
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('spellwheel callback', e.message); return false; }
|
||||
@@ -1485,7 +1518,7 @@ const SD_URL = () => String(process.env.SD_URL || 'https://spookydoors.com').rep
|
||||
const SD_SEASON = { start: '2026-10-04', end: '2026-11-01' }; // Central days, end exclusive (through Halloween night); start moved up from 10-17 (Marty, 2026-10-02)
|
||||
const sdGoldenBonus = () => { const n = Number(ads.rates().goldenBonusCandy); return Number.isFinite(n) && n >= 0 ? Math.round(n) : 2; }; // extra candy on a Golden Door
|
||||
const sdSign = p => drB64u(crypto.createHmac('sha256', SD_SECRET()).update(p).digest());
|
||||
function sdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + sdSign(payload); }
|
||||
function sdMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + sdSign(payload); }
|
||||
function sdOpen(token, expiredMsg) {
|
||||
if (SD_SECRET().length < 32) return { error: 'Spooky Doors is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -1501,7 +1534,7 @@ const RA_URL = () => String(process.env.RA_URL || 'https://roadagent.app').repla
|
||||
const DOOR_GAMES = () => ({ spookydoors: { name: 'Spooky Doors', secret: SD_SECRET(), url: SD_URL(), hdr: 'SD', back: 'Go back to Spooky Doors and knock again.' },
|
||||
roadagent: { name: 'Road Agent', secret: RA_SECRET(), url: RA_URL(), hdr: 'RA', back: 'Go back to Road Agent and fuel up again.' } });
|
||||
const gSign = (g, p) => drB64u(crypto.createHmac('sha256', g.secret).update(p).digest());
|
||||
function gMint(g, claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + gSign(g, payload); }
|
||||
function gMint(g, claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims, gpClaim(claims))); return drB64u(payload) + '.' + gSign(g, payload); }
|
||||
// open a door token from whichever game signed it: { ok, claims, game } or { error }
|
||||
function doorOpen(token, expiredMsg) {
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
@@ -3046,7 +3079,7 @@ const server = http.createServer(async (req, res) => {
|
||||
let sponsorRef = (acct && acct.sponsorRef) || '';
|
||||
const payload = JSON.stringify({ iat: Date.now(), exp: Date.now() + 5 * 60000, nonce: crypto.randomBytes(12).toString('hex'), memberId: Number(memberId), email: s.email, wallet: (acct && acct.address) || s.address || null, username: (acct && acct.username) || null, sponsorRef: sponsorRef || null, joinedAt: (acct && acct.created) || null,
|
||||
// where they first arrived from, so PolHunter can pay a bounty only for people it sent
|
||||
joinedRef: (acct && acct.joinedRef) || null });
|
||||
joinedRef: (acct && acct.joinedRef) || null, gamePass: gamepass.flag(s.email) });
|
||||
const tok = b64u(payload) + '.' + b64u(crypto.createHmac('sha256', secret).update(payload).digest());
|
||||
res.writeHead(302, { Location: huntUrl + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': 'iap.return=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : '') }); return res.end(); // the loop is closed
|
||||
}
|
||||
@@ -3557,6 +3590,71 @@ const server = http.createServer(async (req, res) => {
|
||||
const s = await auth.fromRequest(req);
|
||||
res.writeHead(302, { Location: (s && s.email) ? g.play : S.open, 'Cache-Control': 'no-store' }); return res.end(); // signed in here: straight into the game, signed in
|
||||
} }
|
||||
// -- Game Pass + account-wide POL caps (2026-10-16, docs/GAME-PASS.md section 3a) --------------------------------------------
|
||||
// Partner auth: each game signs with the shared secret it already holds (its *_SSO_SECRET), 10-minute window.
|
||||
// GET ...?game=<slug>&m=<memberId>&e=<email>&ts=<ms>&sig=hex sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts), who = memberId when > 0, else the lowercased email
|
||||
// POST JSON body with `game`, headers X-Game-Ts (ms) + X-Game-Sig sig = HMAC-SHA256(secret, ts + '\n' + rawBody)
|
||||
// The pass is per ACCOUNT (email): a linked position's member id resolves to the owner's account. Games fail closed.
|
||||
if (p === '/api/partner/player' && req.method === 'GET') {
|
||||
const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game);
|
||||
if (chk.error) return json(res, chk.code, { error: chk.error });
|
||||
const m = Number(u.searchParams.get('m')) || 0, e = String(u.searchParams.get('e') || '').trim().toLowerCase(), ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
|
||||
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:' + (m > 0 ? String(m) : e) + ':' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
|
||||
const r = await gpResolve(m, e); if (!r) return json(res, 404, { error: 'no such member', pass: { active: false, until: null } });
|
||||
const now = gpDevNow(u.searchParams.get('devDay'));
|
||||
return json(res, 200, { ok: true, memberId: r.memberId, username: r.acct.username || null, wallet: r.acct.address || null, suspended: fraud.isSuspended(r.email),
|
||||
pass: gamepass.flag(r.email, now), caps: gamepass.capsFor(r.email, now, game), gamePassEnabled: gamepass.cfg().enabled });
|
||||
}
|
||||
if ((p === '/api/partner/polgrant' || p === '/api/partner/polgrant/void' || p === '/api/partner/tournament/paid') && req.method === 'POST') {
|
||||
let raw; try { raw = (await readRaw(req, 16384)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
const game = String(b.game || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error });
|
||||
const ts = String(req.headers['x-game-ts'] || ''), sig = String(req.headers['x-game-sig'] || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
|
||||
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update(ts + '\n' + raw).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
|
||||
if (p === '/api/partner/tournament/paid') { const r = gamepass.markPaid(b.week, b.place, b.tx, game); if (!r.error) console.log('gamepass prize paid', b.week, '#' + b.place, 'by', game, String(b.tx || '').slice(0, 14)); return json(res, r.error ? 400 : 200, r); }
|
||||
const r = await gpResolve(b.memberId, b.email); if (!r) return json(res, 404, { error: 'no such member' });
|
||||
const now = gpDevNow(b.devDay);
|
||||
if (p.endsWith('/void')) return json(res, 200, gamepass.voidGrant({ game, ref: b.ref }));
|
||||
if (fraud.isSuspended(r.email)) return json(res, 200, { allowed: 0, deferred: 0, pass: false, day: gamepass.dayKey(now), suspended: true }); // nothing is recorded: a cleared account replays the ref later
|
||||
const out = gamepass.grant({ email: r.email, game, kind: b.kind, pol: b.pol, ref: b.ref, now });
|
||||
if (!out.error && out.capHit && !out.repeat) console.log('gamepass cap hit', out.capHit, game, r.email.replace(/^(.).*(@.*)$/, '$1***$2'), out.pass ? 'pass' : 'free', out.enforced ? 'enforced' : 'recorded');
|
||||
return json(res, out.error ? 400 : 200, out);
|
||||
}
|
||||
if (p === '/api/partner/tournament/pending' && req.method === 'GET') { // prize rows the games still have to pay out in POL (admin session may read too)
|
||||
if (!isAdmin(req)) {
|
||||
const game = String(u.searchParams.get('game') || '').toLowerCase(); const chk = gpPartnerCheck(game); if (chk.error) return json(res, chk.code, { error: chk.error });
|
||||
const ts = String(u.searchParams.get('ts') || ''), sig = String(u.searchParams.get('sig') || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
|
||||
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:tournament:' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
|
||||
}
|
||||
return json(res, 200, { ok: true, pending: gamepass.pending() });
|
||||
}
|
||||
if (p === '/api/my/gamepass' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
return json(res, 200, gamepass.view(s.email, gpDevNow(u.searchParams.get('devDay'))));
|
||||
}
|
||||
if (p === '/api/my/gamepass/buy' && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
if (fraud.isSuspended(s.email)) return json(res, 403, { error: 'This account is suspended.' });
|
||||
const b = await readBody(req); const { ids } = await myMemberIds(s);
|
||||
// purchased-grade credits only, from a position's package balance (the PolyWarriors mint rule); devPaid = local tests only
|
||||
const charge = (!IS_PROD && b.devPaid) ? async () => ({ ok: true, campaignId: 0, dev: true }) : (price, label) => ads.gamePurchase(s.email, ids, price, label, 'https://instantadpay.com/my#games', { purchasedOnly: true });
|
||||
const r = await gamepass.buy(s.email, charge, gpDevNow(b.devDay));
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (!IS_PROD && p === '/api/dev/gamepass-purchase' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, { order: await gamepass.onEvent({ type: 'Purchase', priceCents: Number(b.cents) || 500, buyerId: 0, tx: '0x' + crypto.randomBytes(32).toString('hex'), ts: Date.now(), devEmail: b.email }) }); } // local tests only
|
||||
if (p === '/api/admin/gamepass/stats' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, gamepass.adminStats()); }
|
||||
if (p === '/api/admin/gamepass/comp' && req.method === 'POST') { // support: give an account a pass week without a purchase
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); if (!e) return json(res, 400, { error: 'email required' });
|
||||
const r = gamepass.comp(e, String(b.why || 'support').slice(0, 80)); console.log('gamepass comp', e, b.why || ''); return json(res, 200, Object.assign({ ok: true, email: e }, r));
|
||||
}
|
||||
if (p === '/api/admin/gamepass/tournament/run' && req.method === 'POST') { // settle a week by hand (the Monday job normally does this)
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req);
|
||||
const at = /^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) ? Date.parse(b.week + 'T17:00:00Z') : Date.now() - 7 * 86400000;
|
||||
const r = await gamepass.runTournament(at, { force: !!b.force }); return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// -- Games hub (2026-10-01): the registry is here, the live list is site config (gamesLive)
|
||||
if (p === '/api/my/games' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
|
||||
Reference in New Issue
Block a user