-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
250 lines (216 loc) · 7.76 KB
/
Copy pathserver.js
File metadata and controls
250 lines (216 loc) · 7.76 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
const express = require('express');
const cors = require('cors');
const path = require('path');
const admin = require('firebase-admin');
const crypto = require('crypto');
require('dotenv').config();
const fs = require('fs');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// Initialize Firebase Admin if a service account JSON is provided via env or file
let firebaseAdminInitialized = false;
try {
if (process.env.FIREBASE_SERVICE_ACCOUNT) {
// Env contains the full JSON string
const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT);
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });
firebaseAdminInitialized = true;
console.log('Firebase Admin initialized from FIREBASE_SERVICE_ACCOUNT env');
} else {
// Allow pointing to a file path (env) or default to ./firebase-service-account.json
const saPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH || path.join(__dirname, 'firebase-service-account.json');
if (fs.existsSync(saPath)) {
const raw = fs.readFileSync(saPath, 'utf8');
const serviceAccount = JSON.parse(raw);
admin.initializeApp({ credential: admin.credential.cert(serviceAccount) });
firebaseAdminInitialized = true;
console.log(`Firebase Admin initialized from file ${saPath}`);
} else {
console.log('FIREBASE_SERVICE_ACCOUNT not set and no service account file found — running without authentication (development mode)');
}
}
} catch (err) {
console.error('Error initializing Firebase Admin:', err.message || err);
console.log('Running without Firebase authentication (development mode)');
}
// Persistent balances stored on disk (per-user)
const DATA_DIR = path.join(__dirname, 'data');
const BALANCE_FILE = path.join(DATA_DIR, 'balances.json');
let userBalances = {};
function loadBalances() {
try {
if (fs.existsSync(BALANCE_FILE)) {
const raw = fs.readFileSync(BALANCE_FILE, 'utf8');
userBalances = JSON.parse(raw || '{}');
} else {
userBalances = {};
}
} catch (err) {
console.error('Failed to load balances file:', err.message || err);
userBalances = {};
}
}
async function saveBalances() {
try {
await fs.promises.mkdir(DATA_DIR, { recursive: true });
await fs.promises.writeFile(BALANCE_FILE, JSON.stringify(userBalances, null, 2), 'utf8');
} catch (err) {
console.error('Failed to save balances file:', err.message || err);
}
}
function getOrInitializeBalance(uid) {
if (!userBalances || typeof userBalances !== 'object') userBalances = {};
if (!(uid in userBalances)) {
userBalances[uid] = 1000.00;
saveBalances().catch(() => {});
}
return userBalances[uid];
}
// Load balances once at startup
loadBalances();
async function authenticateToken(req, res, next) {
if (!firebaseAdminInitialized) {
req.user = { uid: 'dev-user', email: 'dev@example.com' };
return next();
}
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
const decoded = await admin.auth().verifyIdToken(token);
req.user = decoded;
return next();
} catch (err) {
console.error('Token verification error:', err.message || err);
return res.status(403).json({ error: 'Invalid or expired token' });
}
}
function calculateMultipliers(rows) {
const slots = Math.pow(2, rows);
const multipliers = new Array(slots).fill(1);
for (let i = 0; i < slots; i++) {
const dist = Math.abs(i - (slots - 1) / 2) / ((slots - 1) / 2 || 1);
multipliers[i] = 1 + dist * 9;
}
const p = 1 / slots;
let expected = 0;
for (let i = 0; i < slots; i++) expected += p * multipliers[i];
const target = 0.99;
const scale = expected > 0 ? target / expected : 1;
const scaled = multipliers.map(x => Math.max(0.01, +((x * scale).toFixed(4))));
return scaled;
}
// Simulate ball drop using a binary-tree model
function simulatePlinko(rows = 6) {
const rights = [];
for (let i = 0; i < rows; i++) {
const r = crypto.randomInt(2);
rights.push(r);
}
let finalIndex = 0;
for (let i = 0; i < rows; i++) {
if (rights[i]) {
finalIndex += (Math.pow(2, (rows - i - 1)));
}
}
return { rights, finalIndex };
}
// Backwards-compatible wrapper used by routes
function simulateDrop(rows = 6) {
const { rights, finalIndex } = simulatePlinko(rows);
return { moves: rights, finalIndex };
}
// API Routes
// Get user balance
app.get('/api/balance', authenticateToken, (req, res) => {
const balance = getOrInitializeBalance(req.user.uid);
res.json({ balance });
});
// Get multipliers for the board
app.get('/api/multipliers', (req, res) => {
let rows = parseInt(req.query.rows) || 6;
rows = Math.max(1, Math.min(8, rows)); // limit rows to 1..8 for performance
const multipliers = calculateMultipliers(rows);
res.json({ rows, multipliers });
});
// Drop ball and calculate payout
app.post('/api/drop', authenticateToken, async (req, res) => {
try {
let { bet, rows = 6 } = req.body;
rows = Number(rows) || 6;
rows = Math.max(1, Math.min(8, rows));
const uid = req.user.uid;
if (!bet || bet <= 0) {
return res.status(400).json({ error: 'Invalid bet amount' });
}
const currentBalance = getOrInitializeBalance(uid);
if (bet > currentBalance) {
return res.status(400).json({ error: 'Insufficient balance' });
}
// Calculate multipliers
const multipliers = calculateMultipliers(rows);
// Simulate drop
const { moves, finalIndex: serverFinal } = simulateDrop(rows);
// Recalculate final index from moves to guarantee weighting = 2^(rows - i - 1)
let finalIndex = 0;
for (let i = 0; i < rows; i++) {
if (moves[i]) finalIndex += (1 << (rows - i - 1));
}
if (finalIndex !== serverFinal) {
console.warn(`Recomputed finalIndex ${finalIndex} differs from simulateDrop result ${serverFinal}; using recomputed value.`);
}
const multiplier = multipliers[finalIndex];
const payout = bet * multiplier;
// Update balance
const newBalance = currentBalance - bet + payout;
userBalances[uid] = newBalance;
await saveBalances();
res.json({
balance: newBalance,
multiplier,
payout,
final: finalIndex,
rights: moves,
multipliers
});
} catch (error) {
console.error('Drop error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Reset balance
app.post('/api/reset', authenticateToken, async (req, res) => {
const uid = req.user.uid;
userBalances[uid] = 1000.00;
await saveBalances();
res.json({ balance: 1000.00 });
});
// Debug endpoint: verify an ID token and return decoded token (useful for troubleshooting)
app.post('/api/debug-token', async (req, res) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(400).json({ error: 'No token provided' });
if (!firebaseAdminInitialized) {
return res.json({ message: 'dev-mode', user: { uid: 'dev-user', note: 'server running without firebase-admin' } });
}
try {
const decoded = await admin.auth().verifyIdToken(token);
return res.json({ decoded });
} catch (err) {
console.error('Debug token verify error:', err.message || err);
return res.status(403).json({ error: err.message || String(err) });
}
});
// Serve index.html for all routes (SPA)
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(PORT, () => {
console.log(`Plinko game server running on http://localhost:${PORT}`);
if (!firebaseAdminInitialized) {
console.log('Running in development mode without Firebase authentication');
}
});