diff --git a/ads.js b/ads.js index 1d5720d..3a6f2ef 100644 Binary files a/ads.js and b/ads.js differ diff --git a/public/admin.html b/public/admin.html index 8106cb5..dea90ba 100644 --- a/public/admin.html +++ b/public/admin.html @@ -511,6 +511,6 @@ - + diff --git a/public/assets/admin.js b/public/assets/admin.js index 4b069b8..869e9f1 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -935,10 +935,10 @@ else if (typeof v === 'boolean') html.push('
'); else if (Array.isArray(v) && v.every(x => typeof x === 'number')) html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
'); else if (Array.isArray(v) && v.every(x => x && typeof x === 'object')) { - const cols = [...new Set(v.flatMap(x => Object.keys(x)))]; + const cols = [...new Set(v.flatMap(x => Object.keys(x)))]; const txt = new Set(cols.filter(c => v.some(x => typeof x[c] === 'string'))); // text columns (doorHouseAds) stay text html.push('
' + (hint ? '' + esc(hint) + '' : '') + '' + cols.map(c => '').join('') + '' - + v.map((row, i) => '' + cols.map(c => '').join('') + '').join('') + '
' + esc(c) + '
'); + + v.map((row, i) => '' + cols.map(c => '').join('') + '').join('') + ''); } else if (v && typeof v === 'object') { html.push('
' + (hint ? '' + esc(hint) + '' : '') + '
' + Object.entries(v).map(([sk, sv]) => '').join('') + '
'); @@ -951,7 +951,7 @@ document.querySelectorAll('#ratesForm [data-rk]').forEach(el => { const k = el.dataset.rk, kind = el.dataset.kind; if (kind === 'numlist') out[k] = el.value.split(/[\s,]+/).filter(Boolean).map(Number).filter(n => !isNaN(n)); - else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = Number(i.value); }); return o; }); + else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = i.dataset.str ? i.value.trim() : Number(i.value); }); return o; }); else if (kind === 'object') { const o = {}; el.querySelectorAll('input[data-sub]').forEach(i => { o[i.dataset.sub] = Number(i.value); }); out[k] = o; } else if (el.type === 'checkbox') out[k] = !!el.checked; else if (el.type === 'number') out[k] = Number(el.value); diff --git a/public/assets/door.js b/public/assets/door.js index 4eae853..9e36cee 100644 --- a/public/assets/door.js +++ b/public/assets/door.js @@ -39,7 +39,7 @@ if (r.cap && r.ret) return msg('That is tonight’s doors', 'You have knocked on every door for today. Your candy is safe, and the doors open again at midnight Central.', r.ret, true); $('sdHint').textContent = r.error; $('sdCheck').hidden = true; var bb = $('sdBack'); bb.hidden = false; bb.onclick = function () { location.href = gameHome; }; return; } - $('sdCheck').hidden = true; $('sdHint').textContent = r.host ? 'Visit counted. @' + r.host + ' has a treat for you.' : 'Visit counted. Someone has a treat for you.'; + $('sdCheck').hidden = true; $('sdHint').textContent = r.house ? 'Visit counted. A smaller treat from ' + (r.program || 'the house') + ' is on its way.' : r.host ? 'Visit counted. @' + r.host + ' has a treat for you.' : 'Visit counted. Someone has a treat for you.'; var b = $('sdDone'); b.disabled = false; b.textContent = 'Back to the street'; b.onclick = function () { location.href = r.ret; }; setTimeout(function () { location.href = r.ret; }, 1200); }); @@ -53,7 +53,7 @@ : msg('Nobody’s home', 'The lights are out at this house: there are no member pages or videos left for you right now. No candy here, and this door does not count. Head back and try the next house.', r.ret, true); dwell = r.dwell || 8; left = Math.max(1, dwell - (r.elapsed || 0)); if (r.doors && r.doors.cap) { var ch = $('sdDoors'); ch.textContent = 'Door ' + Math.min(r.doors.cap, (r.doors.used || 0) + 1) + ' of ' + r.doors.cap; ch.hidden = false; } - var who = r.host ? '@' + r.host + '’s door' : 'A member’s door'; + var who = r.house ? 'House ad' : r.host ? '@' + r.host + '’s door' : 'A member’s door'; if (r.mode === 'video') { // no member pages left: a member video ad instead $('sdTitle').textContent = who + ': ' + (r.title || 'member video'); $('sdUrl').textContent = 'video ad'; $('sdHint').textContent = 'You have visited every member page running right now, so this door is a short member video. Keep it playing.'; @@ -66,6 +66,7 @@ ring(); timer = setInterval(tick, 1000); return; } $('sdTitle').textContent = who + ': ' + (r.title || 'member site'); try { $('sdUrl').textContent = new URL(r.target).hostname; } catch (e) {} + if (r.house) $('sdHint').textContent = 'A house ad: a smaller treat while the street’s ads are resting. Stay on this page.'; var f = document.createElement('iframe'); f.src = r.target; f.setAttribute('referrerpolicy', 'no-referrer'); f.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups'); $('sdFrame').innerHTML = ''; $('sdFrame').appendChild(f); var o = $('sdOpen'); o.href = r.target; o.hidden = false; ring(); timer = setInterval(tick, 1000); diff --git a/public/door.html b/public/door.html index 08cefe9..b01b25b 100644 --- a/public/door.html +++ b/public/door.html @@ -44,6 +44,6 @@ a.dr-open{color:var(--moon);font-size:12px} - + diff --git a/qa/door.mjs b/qa/door.mjs index 5ff434e..b073f2b 100644 --- a/qa/door.mjs +++ b/qa/door.mjs @@ -3,7 +3,8 @@ // Boots server.js on its own port with a throwaway DATA_DIR and throwaway SD/DR secrets, plus a mock Spooky Doors // game server that records the signed callbacks. Nothing touches production: SD_URL and DR_URL point at the mock. // Covers: open -> challenge (wrong pick, then right) -> done -> callback signature + receipt, re-open after done, -// "nobody's home" (none=1, door not counted), cap (cap=1), the door/refuel/earn caps staying separate, bad tokens, +// house ads when the street is empty (RM Circle first, then the next program with the player's ref; credits 0, counted), +// "nobody's home" only with doorHouseAds = [] (none=1, door not counted), cap (cap=1), the door/refuel/earn caps staying separate, bad tokens, // and the Games card season window. Exit code 1 on any failure. import http from 'node:http'; import crypto from 'node:crypto'; @@ -100,10 +101,30 @@ try { const again = (await api('/api/door/open?t=' + encodeURIComponent(t1))).j; ok(again && again.done && again.ret === d1.ret, 're-open after done returns the same receipt redirect'); const twice = (await api('/api/door/done', { n: n1, answer: 0 })).j; ok(twice && twice.error, 'a door cannot be completed twice'); - // 2. nobody's home: the only pack is visited, no videos -> none=1 and the door is not counted + // 2. the only pack is visited and there are no videos: a house ad (one of Marty's programs) for a smaller treat const n2 = crypto.randomBytes(12).toString('hex'); - const o2 = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2, ret: SD + '/play?door=' + n2 })))).j; - ok(o2 && o2.none && o2.why === 'empty' && o2.ret === SD + '/play?door=' + n2 + '&none=1', 'nothing to serve -> ret&none=1', JSON.stringify(o2)); + const o2 = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, username: 'qadoor', nonce: n2, ret: SD + '/play?door=' + n2 })))).j; + ok(o2 && o2.mode === 'visit' && o2.house === true && o2.program === 'RM Circle' && o2.host === null && o2.target === 'https://rmcircle.team/' && o2.dwell === 2, 'nothing to serve -> a house ad (RM Circle, plain url)', JSON.stringify(o2)); + ok(o2 && o2.doors && o2.doors.used === 1, 'house door shows the door count', JSON.stringify(o2 && o2.doors)); + await sleep(2200); + const hch = (await api('/api/door/challenge?n=' + n2)).j; + const d2 = (await api('/api/door/done', { n: n2, answer: hch.options.indexOf(CAP[hch.prompt]) })).j; + ok(d2 && d2.ok && d2.posted === true && d2.house === true && d2.program === 'RM Circle' && d2.host === null, 'house door done + callback posted', JSON.stringify(d2 && { ok: d2.ok, posted: d2.posted, house: d2.house, program: d2.program })); + const hr = d2 && verify(new URL(d2.ret).searchParams.get('r')); + ok(hr && hr.kind === 'door-receipt' && hr.nonce === n2 && hr.memberId === 77 && hr.house === true && hr.credits === 0 && hr.host === null && hr.campaignId === 0 && hr.program === 'RM Circle', 'house receipt {house: true, credits: 0, host: null, campaignId: 0, program}', JSON.stringify(hr && { house: hr.house, credits: hr.credits, host: hr.host, campaignId: hr.campaignId, program: hr.program })); + const hb = callbacks[1] && JSON.parse(callbacks[1].raw); + ok(hb && hb.nonce === n2 && hb.house === true && hb.credits === 0 && hb.host === null && hb.program === 'RM Circle' && Object.keys(hb).sort().join() === 'campaignId,credits,host,house,memberId,nonce,program', 'house callback body adds {house, program}', callbacks[1] && callbacks[1].raw); + const camps = (await api('/api/admin/campaigns', null, adminH)).j; const pack = camps && (camps.campaigns || []).find(x => x.id === cid); + ok(pack && pack.imps === 1, 'house door does not touch the pack imps', pack && String(pack.imps)); + // next house door: not the same program twice in a row, and the player's username rides along as the program's own ref link + const n2c = crypto.randomBytes(12).toString('hex'); + const o2c = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2c, ret: SD + '/play?door=' + n2c })))).j; + ok(o2c && o2c.house && o2c.program === 'Drip Runner' && o2c.target === 'https://driprunner.app/r/qadoor' && o2c.doors.used === 2, 'next house door rotates (Drip Runner, /r/) and the first one counted', JSON.stringify(o2c && { program: o2c.program, target: o2c.target, doors: o2c.doors })); + // doorHouseAds = [] turns house doors off: nobody's home again, and the door is not counted + await api('/api/admin/rates', { method: 'PATCH', data: { doorHouseAds: [] } }, adminH); + const n2e = crypto.randomBytes(12).toString('hex'); + const o2e = (await api('/api/door/open?t=' + encodeURIComponent(mint({ kind: 'door', memberId: 77, email: player, nonce: n2e, ret: SD + '/play?door=' + n2e })))).j; + ok(o2e && o2e.none && o2e.why === 'empty' && o2e.ret === SD + '/play?door=' + n2e + '&none=1', 'doorHouseAds [] + nothing to serve -> ret&none=1', JSON.stringify(o2e)); // 2b. doors may repeat a campaign after doorRepeatDays (0 here = no cooldown): the same pack is served again await api('/api/admin/rates', { method: 'PATCH', data: { doorRepeatDays: 0 } }, adminH); diff --git a/server.js b/server.js index d21d87e..8c39196 100644 --- a/server.js +++ b/server.js @@ -1311,7 +1311,7 @@ const doorTokens = persistedMap('door'); // nonce -> { kind, email, memberId, id const sdOrders = persistedMap('sdorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts } const sdIsGameUrl = x => String(x || '').startsWith(SD_URL() + '/'); const sdJoin = (ret, q) => ret + (String(ret).includes('?') ? '&' : '?') + q; // ret is SD_URL/play?door=, so this appends &... -async function sdCallback(body) { // door done: POST {nonce, memberId, campaignId, credits, host}, X-SD-Sig = hex HMAC(secret, ts + "\n" + rawBody) +async function sdCallback(body) { // door done: POST {nonce, memberId, campaignId, credits, host} (+ house, program on a house ad), X-SD-Sig = hex HMAC(secret, ts + "\n" + rawBody) const raw = JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SD_SECRET()).update(ts + '\n' + raw).digest('hex'); try { const r = await fetch(SD_URL() + '/api/door/callback', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SD-Ts': ts, 'X-SD-Sig': sig }, body: raw, signal: AbortSignal.timeout(8000) }); return r.ok; } @@ -1325,6 +1325,25 @@ async function sdShopCallback(cbUrl, receipt) { async function sdHost(campaignId) { try { const c = await ads.campaignById(campaignId); if (!c || !c.owner) return null; const a = await accounts.byEmail(String(c.owner).toLowerCase()); return (a && a.username) || null; } catch (e) { return null; } } +// house ads (2026-10-02): when a door finds no visit pack and no video, one of Marty's own programs (rates.doorHouseAds) +// instead of "Nobody's home". Never the same one twice in a row for a member; otherwise the one least recently shown to +// them today. The player's own IAP username rides along where the program takes a share link (ref with {u}). +const doorHouse = persistedMap('doorhouse'); // email -> { ts, day, last, shown: { program: ts } } +function doorHouseList() { + const l = ads.rates().doorHouseAds; + return (Array.isArray(l) ? l : []).filter(x => x && String(x.name || '').trim() && /^https:\/\/[^\s"'<>]+$/i.test(String(x.url || ''))).slice(0, 20); +} +async function doorHousePick(email, claimedUsername) { + const list = doorHouseList(); if (!list.length) return null; + const day = todayCT(); const prev = doorHouse.get(email) || {}; const shown = prev.day === day ? Object.assign({}, prev.shown) : {}; + const pool = list.length > 1 ? list.filter(x => x.name !== prev.last) : list; + const h = pool.slice().sort((a, b) => (shown[a.name] || 0) - (shown[b.name] || 0))[0]; // never shown today sorts first, list order breaks ties + shown[h.name] = Date.now(); doorHouse.set(email, { ts: Date.now(), day, last: h.name, shown }); + let username = null; try { const a = await accounts.byEmail(email); username = (a && a.username) || null; } catch (e) {} + if (!username && claimedUsername) username = String(claimedUsername); + const withRef = username && /^[A-Za-z0-9_.-]{1,40}$/.test(username) && /^https:\/\/[^\s"'<>]*\{u\}/i.test(String(h.ref || '')); + return { name: String(h.name).trim().slice(0, 60), title: String(h.title || h.name).trim().slice(0, 120), target: withRef ? String(h.ref).replace('{u}', encodeURIComponent(username)) : String(h.url) }; +} function sdPage(res, code, title, inner) { res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); res.end('' + gkEsc(title) + ' | InstantAdPay' @@ -2806,14 +2825,19 @@ const server = http.createServer(async (req, res) => { if (ad) t = { kind: 'visit', email, memberId: Number(c.memberId) || 0, id: ad.id, title: ad.title, target: ad.target, ts: Date.now(), ret: c.ret, challenge: null, done: false }; else { // every visit pack already visited: a member video ad instead, one door per video per person const v = await ads.serveVideo(Object.assign({ excludeEmail: email, refuel: true }, viewerGeo(req))); - if (!v) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') }); - t = { kind: 'video', email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + if (v) t = { kind: 'video', email, memberId: Number(c.memberId) || 0, id: v.id, title: v.title, videoUrl: v.videoUrl, secs: v.watchSecs, width: v.width, height: v.height, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + else { // nothing left on the street: a house ad (one of Marty's programs, a smaller treat); none=1 only when the list is empty + const h = await doorHousePick(email, c.username); + if (!h) return json(res, 200, { none: true, why: 'empty', ret: sdJoin(c.ret, 'none=1') }); + t = { kind: 'house', email, memberId: Number(c.memberId) || 0, id: 0, program: h.name, title: h.title, target: h.target, ts: Date.now(), ret: c.ret, challenge: null, done: false }; + } } - t.host = await sdHost(t.id); + t.host = t.kind === 'house' ? null : await sdHost(t.id); doorTokens.set(c.nonce, t); } const doors = { used: status.count, cap: status.cap }; if (t.kind === 'video') return json(res, 200, { mode: 'video', title: t.title, host: t.host || null, doors, video: { url: t.videoUrl, width: t.width, height: t.height }, dwell: t.secs, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); + if (t.kind === 'house') return json(res, 200, { mode: 'visit', house: true, program: t.program, title: t.title, host: null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); return json(res, 200, { mode: 'visit', title: t.title, host: t.host || null, doors, target: t.target, dwell: ads.rates().visitDwellSeconds || 8, ret: t.ret, elapsed: Math.floor((Date.now() - t.ts) / 1000) }); } if (p === '/api/door/challenge' && req.method === 'GET') { @@ -2838,6 +2862,10 @@ const server = http.createServer(async (req, res) => { const tier = await ads.chargeVideoView(t.id); // the advertiser is charged one view, as on the Watch tab if (!tier) return json(res, 400, { error: 'That video just ran out of budget. Go back and try another door.' }); await ads.markVideoSeen(t.email, t.id); credits = tier.cost; + } else if (t.kind === 'house') { // no advertiser and no campaign imps, but it uses one of today's doors + const r = await ads.markHouseDoor(t.email); + if (r.error) return json(res, 400, { error: r.error, cap: true, ret: sdJoin(t.ret, 'cap=1') }); + credits = 0; } else { const r = await ads.completeVisit(t.email, t.id, { reward: false, kind: 'door', note: 'Spooky Doors door' }); if (r.error) return json(res, 400, r); @@ -2845,11 +2873,12 @@ const server = http.createServer(async (req, res) => { } t.done = true; const host = t.host || null; - const posted = await sdCallback({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }); - const receipt = sdMint({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, 24 * 3600000); + const house = t.kind === 'house' ? { house: true, program: t.program } : {}; // a house ad: credits 0, host null, campaignId 0 + const posted = await sdCallback(Object.assign({ nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house)); + const receipt = sdMint(Object.assign({ kind: 'door-receipt', nonce, memberId: t.memberId, campaignId: t.id, credits, host }, house), 24 * 3600000); t.doneRet = sdJoin(t.ret, 'ok=1&r=' + encodeURIComponent(receipt)); doorTokens.set(nonce, t); - return json(res, 200, { ok: true, posted, host, ret: t.doneRet }); + return json(res, 200, Object.assign({ ok: true, posted, host, ret: t.doneRet }, house)); } // -- Games hub (2026-10-01): the registry is here, the live list is site config (gamesLive) if (p === '/api/my/games' && req.method === 'GET') {