-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpost.ts
More file actions
364 lines (341 loc) · 9.63 KB
/
post.ts
File metadata and controls
364 lines (341 loc) · 9.63 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/**
* POST /api/telegram handler (init data verify + DB upsert).
* Loaded only for POST so GET stays fast. Lives under app/telegram; api/telegram.ts imports this.
*/
import crypto from 'crypto';
import {
normalizeUsername,
upsertUserFromTma,
} from '../database/users.js';
import { getDefaultWalletByUsername } from '../database/wallets.js';
const LOG_TAG = '[api/telegram]';
function log(msg: string, detail?: Record<string, unknown>) {
const payload = detail ? ` ${JSON.stringify(detail)}` : '';
console.log(`${LOG_TAG} ${msg}${payload}`);
}
function logErr(msg: string, err: unknown) {
console.error(
`${LOG_TAG} ${msg}`,
err instanceof Error ? err.message : err,
);
if (err instanceof Error && err.stack) console.error(err.stack);
}
type TelegramUserPayload = {
id?: number;
username?: string;
first_name?: string;
last_name?: string;
language_code?: string;
[key: string]: unknown;
};
type VerifiedInitData = {
auth_date?: string;
query_id?: string;
user?: TelegramUserPayload;
[key: string]: unknown;
};
const TELEGRAM_WEBAPP_PUBLIC_KEY_RAW = Buffer.from(
'e7bf03a2fa4602af4580703d88dda5bb59f32ed8b02a56c187fe7d34caed242d',
'hex',
);
const ED25519_SPKI_HEADER = Buffer.from(
'302a300506032b6570032100',
'hex',
);
const TELEGRAM_WEBAPP_PUBLIC_KEY = crypto.createPublicKey({
key: Buffer.concat([
ED25519_SPKI_HEADER,
Buffer.from([0]),
TELEGRAM_WEBAPP_PUBLIC_KEY_RAW,
]),
format: 'der',
type: 'spki',
});
function verifyTelegramWebAppInitData(
initData: string,
botToken: string,
maxAgeSeconds: number = 24 * 3600,
): VerifiedInitData | null {
if (!initData || !botToken) return null;
try {
const params = new URLSearchParams(initData);
const data: Record<string, string> = {};
for (const [key, value] of params.entries()) data[key] = value;
const authDateStr = data['auth_date'];
if (authDateStr) {
const authDate = Number(authDateStr);
if (!Number.isFinite(authDate)) return null;
const now = Math.floor(Date.now() / 1000);
if (authDate > now + 60) return null;
if (maxAgeSeconds != null && now - authDate > maxAgeSeconds) {
return null;
}
}
const receivedHash = data['hash'];
const receivedSignature = data['signature'];
if (receivedHash) {
const dataForHash = { ...data };
delete dataForHash['hash'];
const sorted = Object.keys(dataForHash)
.sort()
.map((k) => `${k}=${dataForHash[k]}`)
.join('\n');
const dataCheckString = Buffer.from(sorted, 'utf8');
const secretKey = crypto
.createHmac('sha256', 'WebAppData')
.update(botToken)
.digest();
const computedHash = crypto
.createHmac('sha256', secretKey)
.update(dataCheckString)
.digest('hex');
const valid =
receivedHash.length === computedHash.length &&
crypto.timingSafeEqual(
Buffer.from(receivedHash, 'hex'),
Buffer.from(computedHash, 'hex'),
);
if (!valid) return null;
} else if (receivedSignature) {
const botId = botToken.split(':')[0];
if (!botId) return null;
const dataForSig = { ...data };
delete dataForSig['hash'];
delete dataForSig['signature'];
const sorted = Object.keys(dataForSig)
.sort()
.map((k) => `${k}=${dataForSig[k]}`)
.join('\n');
const dataCheckString = `${botId}:WebAppData\n${sorted}`;
const base64 = receivedSignature
.replace(/-/g, '+')
.replace(/_/g, '/');
const pad = (4 - (base64.length % 4)) % 4;
const sigBuffer = Buffer.from(
base64 + '='.repeat(pad),
'base64',
);
const ok = crypto.verify(
null,
Buffer.from(dataCheckString, 'utf8'),
TELEGRAM_WEBAPP_PUBLIC_KEY,
sigBuffer,
);
if (!ok) return null;
} else return null;
const result: VerifiedInitData = { ...data };
delete result['hash'];
delete result['signature'];
if (data.user) {
try {
result.user = JSON.parse(data.user) as TelegramUserPayload;
} catch {
return null;
}
}
return result;
} catch {
return null;
}
}
/** Get JSON body from Web Request or Node req (Vercel may pass either). */
async function getBody(
request:
| Request
| {
json?: () => Promise<unknown>;
body?: unknown;
on?: (e: string, fn: (c: Buffer) => void) => void;
},
): Promise<unknown> {
if (
typeof (request as { json?: () => Promise<unknown> }).json ===
'function'
) {
return (request as Request).json();
}
const req = request as {
body?: unknown;
on?: (e: string, fn: (c: Buffer) => void) => void;
};
if (req.body != null && typeof req.body === 'object') {
return req.body;
}
if (typeof req.on === 'function') {
const chunks: Buffer[] = [];
return new Promise<unknown>((resolve, reject) => {
(req as NodeJS.ReadableStream).on(
'data',
(c: Buffer) => chunks.push(c),
);
(req as NodeJS.ReadableStream).on('end', () => {
try {
const raw = Buffer.concat(chunks).toString('utf8');
resolve(raw ? JSON.parse(raw) : null);
} catch (e) {
reject(e);
}
});
(req as NodeJS.ReadableStream).on('error', reject);
});
}
return null;
}
export async function handlePost(
request: Request | { json?: () => Promise<unknown>; body?: unknown },
): Promise<Response> {
const startMs = Date.now();
log('post_start', { elapsedMs: 0 });
let body: any;
try {
body = await getBody(request);
if (body == null) throw new Error('no_body');
log('body_parsed', { elapsedMs: Date.now() - startMs });
} catch (e) {
logErr('body_parse_failed', e);
return new Response(
JSON.stringify({ ok: false, error: 'bad_json' }),
{
status: 400,
headers: { 'content-type': 'application/json' },
},
);
}
const initData =
typeof body?.initData === 'string' ? body.initData : '';
if (!initData) {
log('reject', {
reason: 'missing_initData',
elapsedMs: Date.now() - startMs,
});
return new Response(
JSON.stringify({ ok: false, error: 'missing_initData' }),
{
status: 400,
headers: { 'content-type': 'application/json' },
},
);
}
log('initData_received', {
initDataLength: initData.length,
elapsedMs: Date.now() - startMs,
});
const botToken = (process.env.BOT_TOKEN || '').trim();
if (!botToken) {
log('reject', {
reason: 'bot_token_not_configured',
elapsedMs: Date.now() - startMs,
});
return new Response(
JSON.stringify({ ok: false, error: 'bot_token_not_configured' }),
{
status: 500,
headers: { 'content-type': 'application/json' },
},
);
}
const verifyStart = Date.now();
const verified = verifyTelegramWebAppInitData(initData, botToken);
log('verify_done', {
ok: !!verified,
verifyMs: Date.now() - verifyStart,
elapsedMs: Date.now() - startMs,
});
if (!verified) {
log('reject', {
reason: 'invalid_initdata',
elapsedMs: Date.now() - startMs,
});
return new Response(
JSON.stringify({ ok: false, error: 'invalid_initdata' }),
{
status: 401,
headers: { 'content-type': 'application/json' },
},
);
}
const user: TelegramUserPayload =
verified.user && typeof verified.user === 'object'
? (verified.user as TelegramUserPayload)
: {};
const telegramUsername = normalizeUsername(user.username);
if (!telegramUsername) {
log('reject', {
reason: 'username_required',
elapsedMs: Date.now() - startMs,
});
return new Response(
JSON.stringify({ ok: false, error: 'username_required' }),
{
status: 400,
headers: { 'content-type': 'application/json' },
},
);
}
log('username_ok', {
telegramUsername,
elapsedMs: Date.now() - startMs,
});
const locale =
typeof user.language_code === 'string'
? user.language_code
: null;
const dbStart = Date.now();
try {
await upsertUserFromTma({ telegramUsername, locale });
const wallet = await getDefaultWalletByUsername(telegramUsername);
log('db_upsert_done', {
dbMs: Date.now() - dbStart,
elapsedMs: Date.now() - startMs,
hasWallet: !!wallet,
});
if (wallet) {
log('success', {
telegramUsername,
hasWallet: true,
totalMs: Date.now() - startMs,
});
return new Response(
JSON.stringify({
ok: true,
telegram_username: telegramUsername,
has_wallet: true,
wallet: {
id: wallet.id,
wallet_address: wallet.wallet_address,
wallet_blockchain: wallet.wallet_blockchain,
wallet_net: wallet.wallet_net,
type: wallet.type,
label: wallet.label,
is_default: wallet.is_default,
source: wallet.source,
},
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
}
log('success', {
telegramUsername,
hasWallet: false,
totalMs: Date.now() - startMs,
});
return new Response(
JSON.stringify({
ok: true,
telegram_username: telegramUsername,
has_wallet: false,
wallet_required: true,
}),
{ status: 200, headers: { 'content-type': 'application/json' } },
);
} catch (e) {
logErr('db_upsert_failed', e);
return new Response(
JSON.stringify({ ok: false, error: 'db_error' }),
{
status: 500,
headers: { 'content-type': 'application/json' },
},
);
}
}