grasp-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of grasp-sdk might be problematic. Click here for more details.

@@ -0,0 +1,378 @@
1
+ import { chromium } from 'playwright-extra';
2
+ import StealthPlugin from 'puppeteer-extra-plugin-stealth';
3
+ import httpProxy from 'http-proxy';
4
+ import http from 'http';
5
+
6
+ import { Logtail } from '@logtail/node';
7
+ import * as Sentry from "@sentry/node";
8
+
9
+ console.log(`💬 ${JSON.stringify(process.env)}`)
10
+
11
+ const logtail = new Logtail(process.env.BS_SOURCE_TOKEN, {
12
+ endpoint: `https://${process.env.BS_INGESTING_HOST}`,
13
+ });
14
+
15
+ Sentry.init({
16
+ dsn: process.env.SENTRY_DSN,
17
+
18
+ // Setting this option to true will send default PII data to Sentry.
19
+ // For example, automatic IP address collection on events
20
+ sendDefaultPii: true,
21
+ _experiments: {
22
+ enableLogs: true, // 启用日志功能
23
+ },
24
+ });
25
+
26
+ const logger = {
27
+ info: async (message, context) => {
28
+ Sentry.logger.info(message, context);
29
+ return logtail.info(message, context);
30
+ },
31
+ warn: async (message, context) => {
32
+ Sentry.logger.warn(message, context);
33
+ return logtail.warn(message, context);
34
+ },
35
+ error: async (message, context) => {
36
+ Sentry.logger.error(message, context);
37
+ return logtail.error(message, context);
38
+ },
39
+ }
40
+
41
+ function parseWebSocketFrame(buffer) {
42
+ if (buffer.length < 2) {
43
+ throw new Error('Incomplete WebSocket frame.');
44
+ }
45
+
46
+ const firstByte = buffer.readUInt8(0);
47
+ const fin = (firstByte & 0x80) !== 0;
48
+ const opcode = firstByte & 0x0f;
49
+
50
+ // 仅处理文本帧(opcode 为 0x1)
51
+ if (opcode !== 0x1) {
52
+ throw new Error(`Unsupported opcode: ${opcode}`);
53
+ }
54
+
55
+ const secondByte = buffer.readUInt8(1);
56
+ const isMasked = (secondByte & 0x80) !== 0;
57
+ let payloadLength = secondByte & 0x7f;
58
+ let offset = 2;
59
+
60
+ if (payloadLength === 126) {
61
+ if (buffer.length < offset + 2) {
62
+ throw new Error('Incomplete extended payload length.');
63
+ }
64
+ payloadLength = buffer.readUInt16BE(offset);
65
+ offset += 2;
66
+ } else if (payloadLength === 127) {
67
+ if (buffer.length < offset + 8) {
68
+ throw new Error('Incomplete extended payload length.');
69
+ }
70
+ // 注意:JavaScript 无法精确表示超过 2^53 的整数
71
+ const highBits = buffer.readUInt32BE(offset);
72
+ const lowBits = buffer.readUInt32BE(offset + 4);
73
+ payloadLength = highBits * 2 ** 32 + lowBits;
74
+ offset += 8;
75
+ }
76
+
77
+ let maskingKey;
78
+ if (isMasked) {
79
+ if (buffer.length < offset + 4) {
80
+ throw new Error('Incomplete masking key.');
81
+ }
82
+ maskingKey = buffer.slice(offset, offset + 4);
83
+ offset += 4;
84
+ }
85
+
86
+ if (buffer.length < offset + payloadLength) {
87
+ throw new Error('Incomplete payload data.');
88
+ }
89
+
90
+ const payloadData = buffer.slice(offset, offset + payloadLength);
91
+
92
+ if (isMasked) {
93
+ for (let i = 0; i < payloadLength; i++) {
94
+ payloadData[i] ^= maskingKey[i % 4];
95
+ }
96
+ }
97
+
98
+ return payloadData.toString('utf8');
99
+ }
100
+
101
+ const sandboxId = process.env.SANDBOX_ID;
102
+ const cdpPort = Number(process.env.CDP_PORT);
103
+ const headless = process.env.HEADLESS !== 'false';
104
+ const enableAdblock = process.env.ADBLOCK !== 'false';
105
+ const timeoutMS = process.env.SANBOX_TIMEOUT;
106
+ const workspace = process.env.WORKSPACE;
107
+ const args = [];
108
+
109
+ try {
110
+ console.log('🚀 Starting Chromium browser with CDP...');
111
+
112
+ chromium.use(StealthPlugin());
113
+
114
+ const adblockPlugin = '/home/user/.config/google-chrome/Default/Extensions/adblock';
115
+
116
+ args.push(
117
+ `--remote-debugging-port=${cdpPort}`,
118
+ '--no-sandbox',
119
+ '--disable-setuid-sandbox',
120
+ '--disable-dev-shm-usage',
121
+ '--disable-gpu',
122
+ '--no-first-run',
123
+ '--no-default-browser-check',
124
+ '--disable-background-timer-throttling',
125
+ '--disable-backgrounding-occluded-windows',
126
+ '--disable-renderer-backgrounding',
127
+ ...JSON.parse(process.env.BROWSER_ARGS),
128
+ );
129
+
130
+ if (headless) {
131
+ args.push('--headless=new');
132
+ }
133
+
134
+ if(enableAdblock) {
135
+ args.push(...[
136
+ `--disable-extensions-except=${adblockPlugin}`,
137
+ `--load-extension=${adblockPlugin}`,
138
+ ])
139
+ }
140
+
141
+ const browser = await chromium.launch({
142
+ headless,
143
+ args,
144
+ timeout: Number(process.env.LAUNCH_TIMEOUT),
145
+ // @ts-ignore
146
+ userDataDir: '/home/user/.browser-context',
147
+ });
148
+
149
+ console.log('🎉 Chromium browser launched successfully');
150
+ console.log(`✨ CDP server available at: http://localhost:${cdpPort}`);
151
+ console.log(`✨ WebSocket endpoint: ws://localhost:${cdpPort}`);
152
+
153
+ // Keep the process alive
154
+ process.on('SIGTERM', async () => {
155
+ console.log('Received SIGTERM, closing browser...');
156
+ await logger.warn('Received SIGTERM signal', { sandboxId });
157
+ Sentry.addBreadcrumb({
158
+ category: 'process',
159
+ message: 'Received SIGTERM signal',
160
+ level: 'info',
161
+ data: { sandboxId }
162
+ });
163
+ await browser.close();
164
+ process.exit(0);
165
+ });
166
+
167
+ process.on('SIGINT', async () => {
168
+ console.log('Received SIGINT, closing browser...');
169
+ await logger.warn('Received SIGINT signal', { sandboxId });
170
+ Sentry.addBreadcrumb({
171
+ category: 'process',
172
+ message: 'Received SIGINT signal',
173
+ level: 'info',
174
+ data: { sandboxId }
175
+ });
176
+ await browser.close();
177
+ process.exit(0);
178
+ });
179
+
180
+ // 创建代理服务:从 ${this.config.cdpPort! + 1} 转发到 127.0.0.1:${this.config.cdpPort!}
181
+ const proxy = httpProxy.createProxyServer({
182
+ target: `http://127.0.0.1:${cdpPort}`,
183
+ ws: true, // 支持 WebSocket
184
+ changeOrigin: true
185
+ });
186
+
187
+ // 监听 WebSocket 事件
188
+ proxy.on('open', () => {
189
+ console.log('🔌 CDP WebSocket connection established');
190
+ logger.info('CDP WebSocket connection established', { sandboxId });
191
+ Sentry.addBreadcrumb({
192
+ category: 'websocket',
193
+ message: 'CDP connection established',
194
+ level: 'info',
195
+ data: { sandboxId }
196
+ });
197
+ });
198
+
199
+ proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => {
200
+ console.log('📡 New CDP WebSocket connection request:', req.url);
201
+ logger.info('New CDP WebSocket connection request', { url: req.url, sandboxId });
202
+ Sentry.addBreadcrumb({
203
+ category: 'websocket',
204
+ message: 'New CDP connection request',
205
+ level: 'info',
206
+ data: { url: req.url, sandboxId }
207
+ });
208
+ });
209
+
210
+ proxy.on('error', (err, req, res) => {
211
+ console.error('❌ CDP WebSocket proxy error:', err);
212
+ logger.error('CDP WebSocket proxy error', { error: err.message, url: req?.url, sandboxId });
213
+ Sentry.captureException(err, {
214
+ tags: { type: 'websocket_proxy_error', sandboxId },
215
+ extra: { url: req?.url }
216
+ });
217
+ });
218
+
219
+ proxy.on('close', async (req, socket, head) => {
220
+ console.log('🔒 CDP WebSocket connection closed');
221
+ await logger.info('CDP WebSocket connection closed', { sandboxId });
222
+ Sentry.addBreadcrumb({
223
+ category: 'websocket',
224
+ message: 'CDP connection closed',
225
+ level: 'info',
226
+ data: { sandboxId }
227
+ });
228
+ process.exit(0);
229
+ });
230
+
231
+ const server = http.createServer(async (req, res) => {
232
+ if (req.url === '/json/version' || req.url === '/json/version/') {
233
+ try {
234
+ // 向本地 CDP 发请求,获取原始 JSON
235
+ const jsonRes = await fetch(`http://127.0.0.1:${cdpPort}/json/version`);
236
+ const data = await jsonRes.json();
237
+ // 替换掉本地的 WebSocket 地址为代理暴露地址
238
+ data.webSocketDebuggerUrl = data.webSocketDebuggerUrl.replace(
239
+ `ws://127.0.0.1:${cdpPort}`,
240
+ `wss://${req.headers.host}`
241
+ );
242
+ await logger.info('CDP version info requested', { url: req.url, response: data, sandboxId });
243
+ Sentry.addBreadcrumb({
244
+ category: 'http',
245
+ message: 'CDP version info requested',
246
+ level: 'info',
247
+ data: { url: req.url, response: data, sandboxId }
248
+ });
249
+ res.writeHead(200, { 'Content-Type': 'application/json' });
250
+ res.end(JSON.stringify(data));
251
+ } catch(ex) {
252
+ console.error('Failed to fetch CDP version:', ex.message);
253
+ await logger.error('Failed to fetch CDP version', { error: ex.message, sandboxId });
254
+ Sentry.captureException(ex, {
255
+ tags: { type: 'cdp_version_error', sandboxId }
256
+ });
257
+ res.writeHead(500);
258
+ res.end('Internal Server Error');
259
+ }
260
+ } else {
261
+ proxy.web(req, res, {}, async (err) => {
262
+ console.error('Proxy error:', err);
263
+ await logger.error('HTTP proxy error', { error: err.message, url: req.url, sandboxId });
264
+ Sentry.captureException(err, {
265
+ tags: { type: 'proxy_error', sandboxId },
266
+ extra: { url: req.url }
267
+ });
268
+ res.writeHead(502);
269
+ res.end('Bad gateway');
270
+ });
271
+ }
272
+ });
273
+
274
+ server.on('upgrade', (req, socket, head) => {
275
+ // 监听 WebSocket 数据
276
+ let _buffers = [];
277
+ socket.on('data', (data) => {
278
+ let message = '';
279
+ try {
280
+ _buffers.push(data);
281
+ // console.log(`💬 ${_buffers.length}`);
282
+ message = parseWebSocketFrame(Buffer.concat(_buffers)); // 复制data不能破坏原始数据
283
+ _buffers.length = 0;
284
+ if (message.startsWith('{')){ // 只解析 JSON 消息
285
+ const parsed = JSON.parse(message);
286
+ console.log('📨 CDP WebSocket message:', parsed);
287
+ logger.info('CDP WebSocket message received', {
288
+ data: parsed,
289
+ sandboxId: process.env.SANDBOX_ID,
290
+ });
291
+ Sentry.addBreadcrumb({
292
+ category: 'websocket',
293
+ message: 'CDP message received',
294
+ level: 'debug',
295
+ data: { ...parsed, sandboxId }
296
+ });
297
+ }
298
+ } catch (err) {
299
+ const msg = err.message;
300
+ if(!msg.includes('Incomplete')) {
301
+ // 记录解析错误
302
+ console.warn('⚠️ Failed to parse CDP WebSocket message:', err.message, _buffers.length);
303
+ _buffers.length = 0;
304
+ Sentry.captureException(err, {
305
+ tags: { type: 'websocket_error', sandboxId }
306
+ });
307
+ logger.warn('Failed to parse CDP WebSocket message', {
308
+ error: err.message,
309
+ data: message,
310
+ sandboxId: process.env.SANDBOX_ID
311
+ });
312
+ }
313
+ }
314
+ });
315
+
316
+ socket.on('error', (err) => {
317
+ console.error('❌ CDP WebSocket error:', err);
318
+ logger.error('CDP WebSocket error', { error: err.message, sandboxId });
319
+ Sentry.captureException(err, {
320
+ tags: { type: 'websocket_error', sandboxId }
321
+ });
322
+ });
323
+
324
+ proxy.ws(req, socket, head);
325
+ });
326
+
327
+ server.listen(cdpPort + 1, '0.0.0.0', () => {
328
+ console.log(`🎯 Proxy server listening on http://0.0.0.0:${cdpPort + 1} → http://127.0.0.1:${cdpPort}`);
329
+ logger.info('Proxy server started', {
330
+ port: cdpPort + 1,
331
+ target: cdpPort,
332
+ sandboxId,
333
+ settings: {
334
+ type: 'chromium',
335
+ args,
336
+ headless,
337
+ enableAdblock,
338
+ timeoutMS,
339
+ workspace,
340
+ sandboxId
341
+ },
342
+ });
343
+ Sentry.addBreadcrumb({
344
+ category: 'server',
345
+ message: 'Proxy server started',
346
+ level: 'info',
347
+ data: {
348
+ port: cdpPort + 1,
349
+ target: cdpPort,
350
+ sandboxId,
351
+ settings: {
352
+ type: 'chromium',
353
+ args,
354
+ headless,
355
+ enableAdblock,
356
+ timeoutMS,
357
+ workspace,
358
+ sandboxId
359
+ },
360
+ }
361
+ });
362
+ });
363
+ } catch (ex) {
364
+ console.error('Failed to launch Chromium:', ex);
365
+ logger.error('Failed to launch Chrome', {
366
+ error: ex.message,
367
+ args,
368
+ headless,
369
+ cdpPort,
370
+ enableAdblock,
371
+ sandboxId,
372
+ });
373
+ Sentry.captureException(ex, {
374
+ tags: { type: 'launch_error', sandboxId },
375
+ extra: { args, headless, cdpPort, enableAdblock }
376
+ });
377
+ process.exit(1);
378
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "node",
6
+ "allowSyntheticDefaultImports": true,
7
+ "esModuleInterop": true,
8
+ "allowJs": true,
9
+ "checkJs": true,
10
+ "strict": false,
11
+ "noEmit": true,
12
+ "skipLibCheck": true,
13
+ "forceConsistentCasingInFileNames": true
14
+ },
15
+ "include": [
16
+ "*.mjs",
17
+ "*.js"
18
+ ],
19
+ "exclude": [
20
+ "node_modules"
21
+ ]
22
+ }
@@ -0,0 +1,8 @@
1
+ """Services module for Grasp SDK Python implementation.
2
+
3
+ This module contains core services for sandbox and browser management."""
4
+
5
+ from .sandbox import SandboxService, CommandEventEmitter
6
+ from .browser import BrowserService, CDPConnection
7
+
8
+ __all__ = ['SandboxService', 'CommandEventEmitter', 'BrowserService', 'CDPConnection']