-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
279 lines (248 loc) · 12.4 KB
/
Copy pathserver.js
File metadata and controls
279 lines (248 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// AdSpinner Server — backend for the Antigravity AdSpinner extension.
// Hono + better-sqlite3. Single process, PM2-friendly, no external services.
//
// Model (Kickbacks-style):
// - Advertisers create ads with a bid (millicents per impression) and a budget.
// - Feed is served highest-bid-first among ads with remaining budget.
// - Impressions bill the advertiser at bid rate; clicks bill at CLICK_MULTIPLIER x bid.
// - DEV_SHARE of every billed amount is credited to the device that showed it.
// - Devices register anonymously and get a bearer token; earnings accrue to a ledger.
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { DatabaseSync } from 'node:sqlite';
import { randomBytes, timingSafeEqual } from 'node:crypto';
const PORT = parseInt(process.env.PORT || '8787', 10);
const ADMIN_KEY = process.env.ADMIN_KEY || '';
const DB_PATH = process.env.DB_PATH || './adspinner.db';
const DEV_SHARE = parseFloat(process.env.DEV_SHARE || '0.5'); // 50% to the developer
const CLICK_MULTIPLIER = parseInt(process.env.CLICK_MULTIPLIER || '50', 10); // Kickbacks bills clicks at 50x
const MAX_IMPRESSIONS_PER_MIN = parseInt(process.env.MAX_IMPRESSIONS_PER_MIN || '15', 10); // 5s windows ≈ 12/min
const MAX_CLICKS_PER_MIN = parseInt(process.env.MAX_CLICKS_PER_MIN || '4', 10);
if (!ADMIN_KEY) {
console.error('FATAL: set ADMIN_KEY env var (e.g. ADMIN_KEY=$(openssl rand -hex 24))');
process.exit(1);
}
// ---------- DB ----------
const db = new DatabaseSync(DB_PATH);
db.exec('PRAGMA journal_mode = WAL;');
db.exec(`
CREATE TABLE IF NOT EXISTS devices (
id INTEGER PRIMARY KEY,
token TEXT UNIQUE NOT NULL,
name TEXT,
balance_millicents INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS ads (
id INTEGER PRIMARY KEY,
text TEXT NOT NULL,
url TEXT,
advertiser TEXT,
bid_millicents INTEGER NOT NULL, -- price per impression
budget_millicents INTEGER NOT NULL,
spent_millicents INTEGER NOT NULL DEFAULT 0,
active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY,
device_id INTEGER NOT NULL REFERENCES devices(id),
ad_id INTEGER NOT NULL REFERENCES ads(id),
type TEXT NOT NULL CHECK(type IN ('impression','click')),
billed_millicents INTEGER NOT NULL,
dev_cut_millicents INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_events_device_time ON events(device_id, created_at);
CREATE INDEX IF NOT EXISTS idx_events_ad ON events(ad_id);
`);
// ---------- helpers ----------
const newToken = () => 'dev_' + randomBytes(24).toString('hex');
function safeEqual(a, b) {
const ab = Buffer.from(String(a));
const bb = Buffer.from(String(b));
return ab.length === bb.length && timingSafeEqual(ab, bb);
}
function getDevice(c) {
const auth = c.req.header('authorization') || '';
const token = auth.startsWith('Bearer ') ? auth.slice(7) : (c.req.query('token') || '');
if (!token) return null;
return db.prepare('SELECT * FROM devices WHERE token = ?').get(token) || null;
}
function requireAdmin(c) {
const key = c.req.header('x-admin-key') || '';
return key && safeEqual(key, ADMIN_KEY);
}
const fmt = (mc) => '$' + (mc / 100000).toFixed(4); // millicents → dollars
// ---------- app ----------
const app = new Hono();
// CORS (extension runs in an Electron host; keep permissive for API routes)
app.use('*', async (c, next) => {
await next();
c.header('Access-Control-Allow-Origin', '*');
c.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Admin-Key');
c.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS');
});
app.options('*', (c) => c.body(null, 204));
app.get('/health', (c) => c.json({ ok: true }));
// --- Device registration ---
app.post('/api/register', async (c) => {
let name = null;
try { name = (await c.req.json())?.name ?? null; } catch {}
const token = newToken();
db.prepare('INSERT INTO devices (token, name) VALUES (?, ?)').run(token, name);
return c.json({ token, devShare: DEV_SHARE });
});
// --- Ad feed: highest bid first, budget remaining, active ---
app.get('/feed', (c) => {
const ads = db.prepare(`
SELECT id, text, url FROM ads
WHERE active = 1 AND spent_millicents < budget_millicents
ORDER BY bid_millicents DESC, id ASC
LIMIT 20
`).all();
return c.json(ads.map((a) => ({ id: String(a.id), text: a.text, url: a.url })));
});
// --- Event ingestion: bills advertiser, credits device ---
function insertEvent(device, ad, type) {
const rate = type === 'click' ? ad.bid_millicents * CLICK_MULTIPLIER : ad.bid_millicents;
const remaining = ad.budget_millicents - ad.spent_millicents;
const billed = Math.min(rate, remaining);
if (billed <= 0) return null;
const devCut = Math.floor(billed * DEV_SHARE);
db.exec('BEGIN');
try {
db.prepare('UPDATE ads SET spent_millicents = spent_millicents + ? WHERE id = ?').run(billed, ad.id);
db.prepare('UPDATE devices SET balance_millicents = balance_millicents + ? WHERE id = ?').run(devCut, device.id);
db.prepare('INSERT INTO events (device_id, ad_id, type, billed_millicents, dev_cut_millicents) VALUES (?,?,?,?,?)')
.run(device.id, ad.id, type, billed, devCut);
db.exec('COMMIT');
} catch (e) {
db.exec('ROLLBACK');
throw e;
}
return { billed, devCut };
}
app.post('/api/events', async (c) => {
const device = getDevice(c);
if (!device) return c.json({ error: 'invalid token' }, 401);
let body;
try { body = await c.req.json(); } catch { return c.json({ error: 'bad json' }, 400); }
const type = body.type === 'click' ? 'click' : body.type === 'impression' ? 'impression' : null;
const adId = parseInt(body.adId, 10);
if (!type || !Number.isInteger(adId) || adId <= 0) return c.json({ error: 'need numeric adId > 0 and type (impression|click)' }, 400);
// Anti-fraud: per-device rate caps over the trailing 60s
const cap = type === 'click' ? MAX_CLICKS_PER_MIN : MAX_IMPRESSIONS_PER_MIN;
const recent = db.prepare(
`SELECT COUNT(*) AS n FROM events WHERE device_id = ? AND type = ? AND created_at > datetime('now', '-60 seconds')`
).get(device.id, type).n;
if (recent >= cap) return c.json({ error: 'rate limit', accepted: false }, 429);
const ad = db.prepare('SELECT * FROM ads WHERE id = ? AND active = 1').get(adId);
if (!ad) return c.json({ error: 'unknown or inactive ad', accepted: false }, 404);
const result = insertEvent(device, ad, type);
if (!result) return c.json({ accepted: false, reason: 'budget exhausted' });
const balance = db.prepare('SELECT balance_millicents FROM devices WHERE id = ?').get(device.id).balance_millicents;
return c.json({ accepted: true, earned: result.devCut, balanceMillicents: balance, balance: fmt(balance) });
});
// --- Device stats ---
app.get('/api/stats', (c) => {
const device = getDevice(c);
if (!device) return c.json({ error: 'invalid token' }, 401);
const totals = db.prepare(`
SELECT
SUM(CASE WHEN type='impression' THEN 1 ELSE 0 END) AS impressions,
SUM(CASE WHEN type='click' THEN 1 ELSE 0 END) AS clicks,
COALESCE(SUM(dev_cut_millicents), 0) AS earned
FROM events WHERE device_id = ?
`).get(device.id);
return c.json({
impressions: totals.impressions || 0,
clicks: totals.clicks || 0,
earnedMillicents: totals.earned,
earned: fmt(totals.earned),
balanceMillicents: device.balance_millicents,
balance: fmt(device.balance_millicents),
});
});
// --- Admin: manage ads ---
app.post('/api/ads', async (c) => {
if (!requireAdmin(c)) return c.json({ error: 'unauthorized' }, 401);
let b;
try { b = await c.req.json(); } catch { return c.json({ error: 'bad json' }, 400); }
const text = String(b.text || '').trim().slice(0, 64);
const bid = parseInt(b.bidMillicents, 10);
const budget = parseInt(b.budgetMillicents, 10);
if (!text || !Number.isInteger(bid) || bid <= 0 || !Number.isInteger(budget) || budget <= 0) {
return c.json({ error: 'need text, bidMillicents > 0, budgetMillicents > 0' }, 400);
}
const url = typeof b.url === 'string' && /^https?:\/\//i.test(b.url) ? b.url : null;
const r = db.prepare('INSERT INTO ads (text, url, advertiser, bid_millicents, budget_millicents) VALUES (?,?,?,?,?)')
.run(text, url, b.advertiser || null, bid, budget);
return c.json({ id: r.lastInsertRowid, text, url, bidMillicents: bid, budgetMillicents: budget });
});
app.get('/api/ads', (c) => {
if (!requireAdmin(c)) return c.json({ error: 'unauthorized' }, 401);
const rows = db.prepare(`
SELECT a.*,
(SELECT COUNT(*) FROM events e WHERE e.ad_id = a.id AND e.type='impression') AS impressions,
(SELECT COUNT(*) FROM events e WHERE e.ad_id = a.id AND e.type='click') AS clicks
FROM ads a ORDER BY a.bid_millicents DESC
`).all();
return c.json(rows.map((a) => ({ ...a, spent: fmt(a.spent_millicents), budget: fmt(a.budget_millicents) })));
});
app.patch('/api/ads/:id', async (c) => {
if (!requireAdmin(c)) return c.json({ error: 'unauthorized' }, 401);
const id = parseInt(c.req.param('id'), 10);
let b;
try { b = await c.req.json(); } catch { return c.json({ error: 'bad json' }, 400); }
const ad = db.prepare('SELECT * FROM ads WHERE id = ?').get(id);
if (!ad) return c.json({ error: 'not found' }, 404);
const fields = [];
const vals = [];
if (typeof b.active === 'boolean') { fields.push('active = ?'); vals.push(b.active ? 1 : 0); }
if (Number.isInteger(b.bidMillicents) && b.bidMillicents > 0) { fields.push('bid_millicents = ?'); vals.push(b.bidMillicents); }
if (Number.isInteger(b.budgetMillicents) && b.budgetMillicents > 0) { fields.push('budget_millicents = ?'); vals.push(b.budgetMillicents); }
if (typeof b.text === 'string' && b.text.trim()) { fields.push('text = ?'); vals.push(b.text.trim().slice(0, 64)); }
if (!fields.length) return c.json({ error: 'nothing to update' }, 400);
db.prepare(`UPDATE ads SET ${fields.join(', ')} WHERE id = ?`).run(...vals, id);
return c.json({ ok: true });
});
// --- Admin: overview ---
app.get('/api/overview', (c) => {
if (!requireAdmin(c)) return c.json({ error: 'unauthorized' }, 401);
const o = db.prepare(`
SELECT
(SELECT COUNT(*) FROM devices) AS devices,
(SELECT COUNT(*) FROM ads WHERE active=1) AS activeAds,
(SELECT COUNT(*) FROM events WHERE type='impression') AS impressions,
(SELECT COUNT(*) FROM events WHERE type='click') AS clicks,
(SELECT COALESCE(SUM(billed_millicents),0) FROM events) AS revenue,
(SELECT COALESCE(SUM(dev_cut_millicents),0) FROM events) AS devPayouts
`).get();
return c.json({ ...o, revenue: fmt(o.revenue), devPayouts: fmt(o.devPayouts) });
});
// --- Minimal admin dashboard (paste admin key, view live numbers) ---
app.get('/', (c) =>
c.html(`<!doctype html><meta charset="utf-8"><title>AdSpinner Server</title>
<style>body{font:14px/1.5 system-ui;margin:2rem auto;max-width:760px;padding:0 1rem;color:#222}
input,button{font:inherit;padding:.4rem .6rem}table{border-collapse:collapse;width:100%;margin-top:1rem}
td,th{border:1px solid #ddd;padding:.4rem .6rem;text-align:left}#stats{margin-top:1rem;display:flex;gap:1.5rem;flex-wrap:wrap}
.kpi{background:#f6f6f6;border-radius:8px;padding:.8rem 1.2rem}.kpi b{display:block;font-size:1.4rem}</style>
<h1>AdSpinner Server</h1>
<p>Admin key: <input id="k" type="password" size="40"> <button onclick="load()">Load</button></p>
<div id="stats"></div><div id="ads"></div>
<script>
async function api(p){const r=await fetch(p,{headers:{'X-Admin-Key':document.getElementById('k').value}});if(!r.ok)throw new Error(r.status);return r.json()}
async function load(){try{
const o=await api('/api/overview');
document.getElementById('stats').innerHTML=['devices','activeAds','impressions','clicks','revenue','devPayouts']
.map(k=>'<div class="kpi"><b>'+o[k]+'</b>'+k+'</div>').join('');
const ads=await api('/api/ads');
document.getElementById('ads').innerHTML='<table><tr><th>id</th><th>text</th><th>bid (mc)</th><th>spent/budget</th><th>imps</th><th>clicks</th><th>active</th></tr>'+
ads.map(a=>'<tr><td>'+a.id+'</td><td>'+a.text+'</td><td>'+a.bid_millicents+'</td><td>'+a.spent+' / '+a.budget+'</td><td>'+a.impressions+'</td><td>'+a.clicks+'</td><td>'+a.active+'</td></tr>').join('')+'</table>';
}catch(e){alert('Failed: '+e.message)}}
</script>`)
);
serve({ fetch: app.fetch, port: PORT }, () =>
console.log(`AdSpinner server on :${PORT} (db: ${DB_PATH}, dev share: ${DEV_SHARE}, click x${CLICK_MULTIPLIER})`)
);