File size: 8,850 Bytes
fe2b895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express')
const { chromium } = require('playwright-extra')
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
const crypto = require('crypto')

chromium.use(StealthPlugin())

const app = express()
app.use(express.json())

const sessions = new Map()

const SESSION_TIMEOUT = 10 * 60 * 1000

function makeId() {
  return crypto.randomBytes(8).toString('hex')
}

function touchSession(id) {
  const s = sessions.get(id)
  if (!s) return
  clearTimeout(s.timer)
  s.timer = setTimeout(async () => {
    await s.browser.close().catch(() => {})
    sessions.delete(id)
  }, SESSION_TIMEOUT)
}

async function getSession(id, res) {
  const s = sessions.get(id)
  if (!s) {
    res.status(404).json({ error: 'Session not found or expired' })
    return null
  }
  touchSession(id)
  return s
}

app.post('/session/create', async (req, res) => {
  try {
    const {
      headless = true,
      userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
      viewport = { width: 1280, height: 720 },
      locale = 'en-US',
      extraArgs = []
    } = req.body || {}

    const browser = await chromium.launch({
      headless,
      args: [
        '--no-sandbox',
        '--disable-setuid-sandbox',
        '--disable-dev-shm-usage',
        '--disable-blink-features=AutomationControlled',
        ...extraArgs
      ]
    })

    const context = await browser.newContext({ userAgent, viewport, locale })
    const page = await context.newPage()
    const id = makeId()

    const timer = setTimeout(async () => {
      await browser.close().catch(() => {})
      sessions.delete(id)
    }, SESSION_TIMEOUT)

    sessions.set(id, { browser, context, page, timer, createdAt: Date.now() })

    res.json({ ok: true, sessionId: id })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/goto', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { url, waitUntil = 'networkidle', timeout = 30000 } = req.body
    if (!url) return res.status(400).json({ error: 'Missing url' })
    const response = await s.page.goto(url, { waitUntil, timeout })
    res.json({ ok: true, status: response?.status(), url: s.page.url() })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/content', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const content = await s.page.content()
    const url = s.page.url()
    res.json({ ok: true, url, content })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/cookies', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const cookies = await s.context.cookies()
    const cfClearance = cookies.find(c => c.name === 'cf_clearance')
    const cookieHeader = cookies.map(c => `${c.name}=${c.value}`).join('; ')
    res.json({ ok: true, cookies, cfClearance: cfClearance?.value || null, cookieHeader })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/set-cookies', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { cookies } = req.body
    if (!Array.isArray(cookies)) return res.status(400).json({ error: 'cookies must be array' })
    await s.context.addCookies(cookies)
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/eval', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { script } = req.body
    if (!script) return res.status(400).json({ error: 'Missing script' })
    const result = await s.page.evaluate(script)
    res.json({ ok: true, result })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/click', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { selector, timeout = 5000 } = req.body
    if (!selector) return res.status(400).json({ error: 'Missing selector' })
    await s.page.click(selector, { timeout })
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/type', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { selector, text, delay = 50 } = req.body
    if (!selector || !text) return res.status(400).json({ error: 'Missing selector or text' })
    await s.page.type(selector, text, { delay })
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/wait', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { selector, timeout = 10000, state = 'visible' } = req.body
    if (!selector) return res.status(400).json({ error: 'Missing selector' })
    await s.page.waitForSelector(selector, { timeout, state })
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/screenshot', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { fullPage = false } = req.body || {}
    const buf = await s.page.screenshot({ fullPage, type: 'png' })
    res.set('Content-Type', 'image/png')
    res.send(buf)
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/fetch', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { url, method = 'GET', headers = {}, body } = req.body
    if (!url) return res.status(400).json({ error: 'Missing url' })

    const result = await s.page.evaluate(async ({ url, method, headers, body }) => {
      const r = await fetch(url, { method, headers, body })
      const text = await r.text()
      let data
      try { data = JSON.parse(text) } catch { data = text }
      return { status: r.status, ok: r.ok, data }
    }, { url, method, headers, body })

    res.json({ ok: true, ...result })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.post('/session/:id/headers', async (req, res) => {
  const s = await getSession(req.params.id, res)
  if (!s) return
  try {
    const { headers } = req.body
    if (!headers) return res.status(400).json({ error: 'Missing headers' })
    await s.context.setExtraHTTPHeaders(headers)
    res.json({ ok: true })
  } catch (err) {
    res.status(500).json({ error: err.message })
  }
})

app.get('/session/:id/status', async (req, res) => {
  const s = sessions.get(req.params.id)
  if (!s) return res.status(404).json({ error: 'Session not found' })
  res.json({
    ok: true,
    sessionId: req.params.id,
    url: s.page.url(),
    createdAt: s.createdAt,
    age: Date.now() - s.createdAt
  })
})

app.delete('/session/:id', async (req, res) => {
  const s = sessions.get(req.params.id)
  if (!s) return res.status(404).json({ error: 'Session not found' })
  clearTimeout(s.timer)
  await s.browser.close().catch(() => {})
  sessions.delete(req.params.id)
  res.json({ ok: true, message: 'Session closed' })
})

app.get('/sessions', (req, res) => {
  const list = [...sessions.entries()].map(([id, s]) => ({
    sessionId: id,
    url: s.page.url(),
    createdAt: s.createdAt,
    age: Date.now() - s.createdAt
  }))
  res.json({ ok: true, count: list.length, sessions: list })
})

app.get('/', (req, res) => {
  res.json({
    ok: true,
    name: 'Playwright Browser API',
    endpoints: {
      'POST /session/create': 'Create new browser session',
      'POST /session/:id/goto': 'Navigate to URL { url, waitUntil, timeout }',
      'POST /session/:id/content': 'Get page HTML content',
      'POST /session/:id/cookies': 'Get all cookies + cf_clearance',
      'POST /session/:id/set-cookies': 'Set cookies { cookies: [] }',
      'POST /session/:id/eval': 'Execute JS { script }',
      'POST /session/:id/click': 'Click element { selector }',
      'POST /session/:id/type': 'Type text { selector, text, delay }',
      'POST /session/:id/wait': 'Wait for selector { selector, state, timeout }',
      'POST /session/:id/screenshot': 'Get screenshot (returns image/png)',
      'POST /session/:id/fetch': 'Fetch URL from browser context { url, method, headers, body }',
      'POST /session/:id/headers': 'Set extra HTTP headers { headers: {} }',
      'GET  /session/:id/status': 'Session info',
      'DELETE /session/:id': 'Close session',
      'GET  /sessions': 'List all active sessions'
    }
  })
})

app.listen(7860, () => console.log('Playwright API running on :7860'))