-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
291 lines (254 loc) · 8.13 KB
/
Copy pathserver.ts
File metadata and controls
291 lines (254 loc) · 8.13 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
280
281
282
283
284
285
286
287
288
289
290
291
import express from "express";
import path from "path";
import { createServer as createViteServer } from "vite";
const MOCK_GAMES = [
{
id: "g1",
title: "Cyberpunk 2077",
publisher: "CD PROJEKT RED",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co1r7f.jpg"
},
{
id: "g2",
title: "The Witcher 3: Wild Hunt",
publisher: "CD PROJEKT RED",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co1wyy.jpg"
},
{
id: "g3",
title: "Apex Legends",
publisher: "Electronic Arts",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co1x70.jpg"
},
{
id: "g4",
title: "Destiny 2",
publisher: "Bungie",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co1oj8.jpg"
},
{
id: "g5",
title: "No Man's Sky",
publisher: "Hello Games",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co1vyv.jpg"
},
{
id: "g6",
title: "Baldur's Gate 3",
publisher: "Larian Studios",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co670h.jpg"
},
{
id: "g7",
title: "Starfield",
publisher: "Bethesda Softworks",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co6jof.jpg"
},
{
id: "g8",
title: "Counter-Strike 2",
publisher: "Valve",
imageUrl: "https://images.igdb.com/igdb/image/upload/t_cover_big/co6ntt.jpg"
}
];
import crypto from "crypto";
const authSessions = new Map<string, {
codeVerifier: string;
status: 'PENDING' | 'SUCCESS' | 'FAILED';
tokens?: any;
}>();
let mockSettings = {
streamResolution: "4K (3840x2160)",
frameRate: "120 FPS",
serverLocation: "EU West",
hdr: true,
reflex: true
};
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json());
// --- Real Auth Flow ---
app.get("/api/auth/real/start", (req, res) => {
const sessionId = crypto.randomUUID();
const codeVerifier = crypto.randomBytes(32).toString('base64url');
authSessions.set(sessionId, {
codeVerifier,
status: 'PENDING'
});
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers.host;
// The URL for the QR code
const mobileLink = `${protocol}://${host}/api/auth/real/mobile?sessionId=${sessionId}`;
res.json({ sessionId, qrUrl: mobileLink });
});
app.get('/api/auth/real/mobile', (req, res) => {
const { sessionId } = req.query;
if (!sessionId || !authSessions.has(sessionId as string)) {
return res.status(400).send("Invalid session");
}
const session = authSessions.get(sessionId as string)!;
const codeChallenge = crypto.createHash('sha256').update(session.codeVerifier).digest('base64url');
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers.host;
const redirectUri = `${protocol}://${host}/api/auth/real/callback`;
const params = new URLSearchParams({
client_id: 'ZU7sPN-miLujMD95LfOQ453IB0AtjM8sMyvgJ9wCXEQ',
redirect_uri: redirectUri,
response_type: 'code',
scope: 'openid consent email tk_client age',
code_challenge: codeChallenge,
code_challenge_method: 'S256',
state: sessionId as string
});
res.redirect(`https://login.nvidia.com/authorize?${params.toString()}`);
});
app.get('/api/auth/real/callback', async (req, res) => {
const { code, state, error } = req.query;
if (error || !code || !state) {
if (state && authSessions.has(state as string)) {
authSessions.get(state as string)!.status = 'FAILED';
}
return res.send(`Authentication failed: ${error}`);
}
const session = authSessions.get(state as string);
if (!session) {
return res.status(400).send("Session not found or expired");
}
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers.host;
const redirectUri = `${protocol}://${host}/api/auth/real/callback`;
try {
const tokenRes = await fetch('https://login.nvidia.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
client_id: 'ZU7sPN-miLujMD95LfOQ453IB0AtjM8sMyvgJ9wCXEQ',
grant_type: 'authorization_code',
code: code as string,
redirect_uri: redirectUri,
code_verifier: session.codeVerifier
}).toString()
});
if (!tokenRes.ok) {
const err = await tokenRes.text();
session.status = 'FAILED';
return res.status(400).send(`Token exchange failed: ${err}`);
}
const tokens = await tokenRes.json();
session.status = 'SUCCESS';
session.tokens = tokens;
res.send(`
<html>
<head>
<title>Login Successful</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: sans-serif; background: #0f1011; color: white; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
.box { text-align: center; background: #1a1c1e; padding: 2rem; border-radius: 12px; }
h1 { color: #76b900; }
</style>
</head>
<body>
<div class="box">
<h1>Login Successful!</h1>
<p>You can close this tab and return to the TV.</p>
</div>
</body>
</html>
`);
} catch (e: any) {
session.status = 'FAILED';
res.send(`Token exchange error: ${e.message}`);
}
});
app.get('/api/auth/real/status', (req, res) => {
const { sessionId } = req.query;
const session = authSessions.get(sessionId as string);
if (!session) {
return res.json({ status: 'NOT_FOUND' });
}
res.json({
status: session.status,
tokens: session.tokens
});
});
// --- End Real Auth Flow ---
// --- OpenNOW Backend simulation ---
// Auth/User state (Mocked for Preview)
app.get("/api/auth/session", (req, res) => {
res.json({
authenticated: true,
user: {
username: "PreviewUser_77",
membership: "Ultimate",
hoursPlayed: 142
}
});
});
// Fetch games
app.get("/api/games/featured", (req, res) => {
res.json({
categories: [
{
title: "Play It Now",
games: MOCK_GAMES.slice(0, 4)
},
{
title: "Free-to-Play",
games: [MOCK_GAMES[2], MOCK_GAMES[3], MOCK_GAMES[7]]
},
{
title: "Popular RPGs",
games: [MOCK_GAMES[0], MOCK_GAMES[1], MOCK_GAMES[5], MOCK_GAMES[6]]
}
]
});
});
// Stream Settings API
app.get("/api/settings", (req, res) => {
res.json(mockSettings);
});
app.post("/api/settings", (req, res) => {
mockSettings = { ...mockSettings, ...req.body };
res.json({ success: true, settings: mockSettings });
});
// CloudMatch Simulation (Launch session)
app.post("/api/session/launch", (req, res) => {
const { gameId } = req.body;
const game = MOCK_GAMES.find(g => g.id === gameId);
if (!game) {
return res.status(404).json({ error: "Game not found" });
}
// Simulate CloudMatch connection negotiation time
setTimeout(() => {
res.json({
success: true,
sessionUrl: `rtsp://prod.cloudmatchbeta.nvidiagrid.net/v2/session/${gameId}_preview`,
hardware: "RTX 4080 Super",
resolution: mockSettings.streamResolution
});
}, 1500);
});
// --- End OpenNOW backend ---
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*all', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`OpenNOW TV server running on http://localhost:${PORT}`);
});
}
startServer();