-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
360 lines (314 loc) · 12.6 KB
/
Copy pathserver.js
File metadata and controls
360 lines (314 loc) · 12.6 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
import 'dotenv/config'
import express from 'express'
import multer from 'multer'
import fetch from 'node-fetch'
import FormData from 'form-data'
import helmet from 'helmet'
import rateLimit from 'express-rate-limit'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
const __dirname = dirname(fileURLToPath(import.meta.url))
const app = express()
const upload = multer({ limits: { fileSize: 10 * 1024 * 1024 } })
const PORT = process.env.PORT || 3457
// security headers
app.use(helmet({
contentSecurityPolicy: false, // allow cdn fonts
crossOriginEmbedderPolicy: false
}))
app.disable('x-powered-by')
// api rate limiting: 30 requests per 15 minutes per IP
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
standardHeaders: true,
legacyHeaders: false,
message: { error: 'too many requests, try again later' }
})
// serve frontend - explicitly block sensitive files
const blocklist = ['.env', '.git', 'server.js', 'package.json', 'package-lock.json', 'ecosystem.config.cjs', 'vercel.json']
app.use((req, res, next) => {
const path = req.path.toLowerCase()
if (blocklist.some(b => path.includes(b))) {
return res.status(403).end()
}
next()
})
app.use(express.static(join(__dirname, '.')))
// proxy remove bg
app.post('/api/removebg', apiLimiter, upload.single('image'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'no image' })
try {
const form = new FormData()
form.append('image', req.file.buffer, {
filename: req.file.originalname,
contentType: req.file.mimetype
})
form.append('format', 'png')
form.append('model', 'v1')
const r = await fetch('https://api2.pixelcut.app/image/matte/v1', {
method: 'POST',
headers: {
'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Mobile Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'sec-ch-ua': '"Chromium";v="139", "Not;A=Brand";v="99"',
'x-locale': 'en',
'x-client-version': 'web:pixa.com:4a5b0af2',
'sec-ch-ua-mobile': '?1',
'sec-ch-ua-platform': '"Android"',
'origin': 'https://www.pixa.com',
'sec-fetch-site': 'cross-site',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://www.pixa.com/',
...form.getHeaders()
},
body: form
})
if (!r.ok) {
return res.status(r.status).json({ error: 'upstream error ' + r.status })
}
const buf = Buffer.from(await r.arrayBuffer())
res.set('Content-Type', 'image/png')
res.set('Content-Length', buf.length)
res.send(buf)
} catch (e) {
res.status(500).json({ error: e.message })
}
})
// proxy enhance hd
async function uploadToCatbox(buffer) {
const form = new FormData()
form.append('reqtype', 'fileupload')
form.append('fileToUpload', buffer, { filename: 'image.jpg', contentType: 'image/jpeg' })
const res = await fetch('https://catbox.moe/user/api.php', { method: 'POST', body: form, headers: form.getHeaders() })
if (!res.ok) throw new Error('Catbox upload failed')
return await res.text()
}
async function enhanceViaWebAbility(buffer, scale = '2', model = 'esrgan', mode = 'photo') {
const dataUrl = `data:image/png;base64,${buffer.toString('base64')}`
const payload = { image: dataUrl, scale: String(scale), model, mode }
const res = await fetch('https://www.webability.io/api/upscale-image', {
method: 'POST',
headers: {
'accept': '*/*',
'content-type': 'application/json',
'origin': 'https://www.webability.io',
'referer': 'https://www.webability.io/tools/ai-image-upscaler',
'user-agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Mobile Safari/537.36'
},
body: JSON.stringify(payload)
})
const result = await res.json().catch(() => ({}))
if (!res.ok || result.success === false) throw new Error(result.error || `WebAbility HTTP ${res.status}`)
if (!result.upscaledImageUrl) throw new Error('WebAbility: no image in response')
return result.upscaledImageUrl
}
async function enhanceViaBetabotz(buffer) {
const catboxUrl = await uploadToCatbox(buffer)
const encodedUrl = encodeURIComponent(catboxUrl)
const betabotzKey = process.env.BETABOTZ_API_KEY || 'Btz-Flores'
const apiUrl = `https://api.betabotz.eu.org/api/tools/remini?url=${encodedUrl}&apikey=${betabotzKey}`
const apiRes = await fetch(apiUrl)
const apiJson = await apiRes.json()
if (!apiJson.status || !apiJson.url) throw new Error('Betabotz failed')
if (apiJson.url.endsWith('.bin')) throw new Error('Invalid bin result')
return apiJson.url
}
app.post('/api/enhance', apiLimiter, upload.single('image'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'no image' })
try {
let resultBuffer
// primary: WebAbility upscaler
try {
const upscaledUrl = await enhanceViaWebAbility(req.file.buffer)
const dl = await fetch(upscaledUrl)
if (!dl.ok) throw new Error('WebAbility download failed')
resultBuffer = Buffer.from(await dl.arrayBuffer())
} catch (err) {
console.log('WebAbility failed, falling back to Betabotz...', err.message)
// fallback: Betabotz
const resultUrl = await enhanceViaBetabotz(req.file.buffer)
const imgRes = await fetch(resultUrl)
if (!imgRes.ok) throw new Error('Download enhanced failed')
resultBuffer = Buffer.from(await imgRes.arrayBuffer())
}
if (!resultBuffer || !resultBuffer.length) throw new Error('No result image')
res.set('Content-Type', 'image/jpeg')
res.set('Content-Length', resultBuffer.length)
res.send(resultBuffer)
} catch (e) {
console.error('Enhance API error:', e)
res.status(500).json({ error: e.message })
}
})
// proxy tiktok downloader
app.post('/api/tiktok', apiLimiter, express.json(), async (req, res) => {
const { url } = req.body || {}
if (!url || !/tiktok|douyin/.test(url)) {
return res.status(400).json({ error: 'Invalid TikTok URL' })
}
try {
const [tikwm, oembed] = await Promise.all([
fetch('https://www.tikwm.com/api/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36',
'Referer': 'https://www.tikwm.com/',
'Cookie': 'current_language=en',
},
body: new URLSearchParams({ url, count: 12, cursor: 0, web: 1, hd: 1 }),
}),
fetch('https://www.tiktok.com/oembed?url=' + encodeURIComponent(url), {
headers: { 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36' },
}).then(r => r.ok ? r.json() : {}).catch(() => ({})),
])
if (!tikwm.ok) throw new Error('tikwm ' + tikwm.status)
const json = await tikwm.json()
if (json.code !== 0 || !json.data) throw new Error(json.msg || 'tikwm fail')
const d = json.data
const author = d.author || {}
const result = {
title: d.title || '',
duration: d.duration || 0,
author: { nickname: author.nickname || '', unique_id: author.unique_id || '', avatar: author.avatar || '' },
stats: { views: d.play_count || 0, likes: d.digg_count || 0, comments: d.comment_count || 0, shares: d.share_count || 0 },
music: d.music_info?.play || d.music || '',
music_title: d.music_info?.title || '',
cover: d.cover ? (d.cover.startsWith('http') ? d.cover : 'https://www.tikwm.com' + d.cover) : '',
media: [],
}
if (d.images && d.images.length > 0) {
for (const img of d.images) result.media.push({ type: 'photo', url: img })
} else {
if (d.play) result.media.push({ type: 'nowatermark', url: 'https://www.tikwm.com' + d.play })
if (d.hdplay) result.media.push({ type: 'nowatermark_hd', url: 'https://www.tikwm.com' + d.hdplay })
}
if (oembed.thumbnail_url) result.cover = oembed.thumbnail_url
res.json({ ok: true, result })
} catch (e) {
console.error('[tiktok]', e)
res.status(500).json({ error: e.message })
}
})
// proxy tiktok media download (avoid CORS)
app.get('/api/tiktok-proxy', apiLimiter, async (req, res) => {
const target = req.query.url
if (!target) return res.status(400).json({ error: 'no url' })
try {
const r = await fetch(target, {
headers: {
'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Mobile Safari/537.36',
'Referer': 'https://www.tikwm.com/',
},
})
if (!r.ok) throw new Error('proxy ' + r.status)
const ct = r.headers.get('content-type') || 'application/octet-stream';
const cl = r.headers.get('content-length');
res.set('Content-Type', ct);
if (req.query.filename) res.set('Content-Disposition', `attachment; filename="${req.query.filename}"`);
if (cl) res.set('Content-Length', cl);
r.body.pipe(res);
} catch (e) {
res.status(500).json({ error: e.message })
}
})
// ── Instagram Downloader API ──
app.use(express.json())
const BTZ_KEY = process.env.BTZ_KEY || 'AK-vhgawcjw4b'
async function igScrape(url) {
try {
const params = new URLSearchParams()
params.append('q', url)
params.append('v', 'v2')
const r = await fetch('https://savereels.io/api/ajaxSearch', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K)'
},
body: params.toString()
})
const res = await r.json()
if (res.status !== 'ok') return { status: false }
const links = [...res.data.matchAll(/href="(https:\/\/dl\.snapcdn\.app\/get\?token=[^"]+)"/g)]
.map(m => m[1])
return { status: true, results: [...new Set(links)] }
} catch (e) {
return { status: false, error: e.message }
}
}
app.post('/api/instagram', apiLimiter, async (req, res) => {
let { url } = req.body || {}
if (!url || !/instagram\.com/i.test(url)) {
return res.status(400).json({ error: 'Invalid Instagram URL' })
}
try {
// resolve share links
if (url.includes('instagram.com/share/')) {
const resp = await fetch(url, { redirect: 'follow' })
url = resp.url
}
// primary scraper
let mediaLinks = []
try {
const scraper = await igScrape(url)
if (scraper.status && scraper.results.length > 0) {
mediaLinks = scraper.results
} else {
throw new Error('primary scraper failed')
}
} catch {
// fallback to betabotz
const api = await fetch(`https://api.betabotz.eu.org/api/download/igdowloader?url=${encodeURIComponent(url)}&apikey=${BTZ_KEY}`)
const fallback = await api.json()
if (!fallback || !fallback.status || !Array.isArray(fallback.message)) {
throw new Error('all scrapers failed')
}
mediaLinks = fallback.message.map(m => m._url).filter(Boolean)
}
if (mediaLinks.length === 0) throw new Error('no media found')
// probe content-type for each media
const media = []
for (const link of mediaLinks.slice(0, 5)) {
try {
const head = await fetch(link, { method: 'HEAD', headers: { 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K)' } })
const ct = head.headers.get('content-type') || ''
const type = ct.startsWith('video/') ? 'video' : ct.startsWith('image/') ? 'image' : 'unknown'
media.push({ url: link, type })
} catch {
media.push({ url: link, type: 'unknown' })
}
}
res.json({ ok: true, media })
} catch (e) {
console.error('[instagram]', e)
res.status(500).json({ error: e.message })
}
})
// proxy instagram media download (avoid CORS / CDN blocks)
app.get('/api/ig-proxy', apiLimiter, async (req, res) => {
const target = req.query.url
if (!target) return res.status(400).json({ error: 'no url' })
try {
const r = await fetch(target, {
headers: {
'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Mobile Safari/537.36',
},
})
if (!r.ok) throw new Error('proxy ' + r.status)
const ct = r.headers.get('content-type') || 'application/octet-stream';
const cl = r.headers.get('content-length');
res.set('Content-Type', ct);
if (req.query.filename) res.set('Content-Disposition', `attachment; filename="${req.query.filename}"`);
if (cl) res.set('Content-Length', cl);
r.body.pipe(res);
} catch (e) {
res.status(500).json({ error: e.message })
}
})
app.listen(PORT, () => {
console.log(`ruby-tools server listening on :${PORT}`)
})