scrapfly-sdk 0.11.0 → 0.12.0

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.
Files changed (68) hide show
  1. package/README.md +36 -3
  2. package/esm/browserconfig.d.ts +37 -5
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +51 -3
  5. package/esm/client.d.ts +124 -9
  6. package/esm/client.d.ts.map +1 -1
  7. package/esm/client.js +346 -50
  8. package/esm/crawl.d.ts +58 -1
  9. package/esm/crawl.d.ts.map +1 -1
  10. package/esm/crawl.js +55 -0
  11. package/esm/crawlerconfig.d.ts +41 -3
  12. package/esm/crawlerconfig.d.ts.map +1 -1
  13. package/esm/crawlerconfig.js +93 -2
  14. package/esm/crawlerresult.d.ts +335 -2
  15. package/esm/crawlerresult.d.ts.map +1 -1
  16. package/esm/crawlerresult.js +367 -1
  17. package/esm/errors.d.ts +12 -0
  18. package/esm/errors.d.ts.map +1 -1
  19. package/esm/errors.js +11 -0
  20. package/esm/main.d.ts +4 -4
  21. package/esm/main.d.ts.map +1 -1
  22. package/esm/main.js +3 -3
  23. package/esm/scrapeconfig.d.ts +36 -0
  24. package/esm/scrapeconfig.d.ts.map +1 -1
  25. package/esm/scrapeconfig.js +44 -2
  26. package/esm/types.d.ts.map +1 -1
  27. package/esm/webhookserver.d.ts +33 -15
  28. package/esm/webhookserver.d.ts.map +1 -1
  29. package/esm/webhookserver.js +197 -38
  30. package/package.json +1 -1
  31. package/script/browserconfig.d.ts +37 -5
  32. package/script/browserconfig.d.ts.map +1 -1
  33. package/script/browserconfig.js +51 -3
  34. package/script/client.d.ts +124 -9
  35. package/script/client.d.ts.map +1 -1
  36. package/script/client.js +345 -49
  37. package/script/crawl.d.ts +58 -1
  38. package/script/crawl.d.ts.map +1 -1
  39. package/script/crawl.js +55 -0
  40. package/script/crawlerconfig.d.ts +41 -3
  41. package/script/crawlerconfig.d.ts.map +1 -1
  42. package/script/crawlerconfig.js +94 -3
  43. package/script/crawlerresult.d.ts +335 -2
  44. package/script/crawlerresult.d.ts.map +1 -1
  45. package/script/crawlerresult.js +374 -2
  46. package/script/errors.d.ts +12 -0
  47. package/script/errors.d.ts.map +1 -1
  48. package/script/errors.js +12 -1
  49. package/script/main.d.ts +4 -4
  50. package/script/main.d.ts.map +1 -1
  51. package/script/main.js +9 -2
  52. package/script/scrapeconfig.d.ts +36 -0
  53. package/script/scrapeconfig.d.ts.map +1 -1
  54. package/script/scrapeconfig.js +44 -2
  55. package/script/types.d.ts.map +1 -1
  56. package/script/webhookserver.d.ts +33 -15
  57. package/script/webhookserver.d.ts.map +1 -1
  58. package/script/webhookserver.js +197 -38
  59. package/src/browserconfig.ts +52 -4
  60. package/src/client.ts +413 -51
  61. package/src/crawl.ts +74 -0
  62. package/src/crawlerconfig.ts +115 -5
  63. package/src/crawlerresult.ts +566 -3
  64. package/src/errors.ts +12 -0
  65. package/src/main.ts +25 -2
  66. package/src/scrapeconfig.ts +54 -2
  67. package/src/types.ts +0 -1
  68. package/src/webhookserver.ts +235 -39
@@ -106,6 +106,12 @@ class ScrapeConfig {
106
106
  writable: true,
107
107
  value: false
108
108
  });
109
+ /**
110
+ * Storage for the anti-bot bypass toggle, under its deprecated name.
111
+ * `unblocker` is an accessor over this same field — see below.
112
+ *
113
+ * @deprecated Use {@link ScrapeConfig.unblocker}. `asp` keeps working forever.
114
+ */
109
115
  Object.defineProperty(this, "asp", {
110
116
  enumerable: true,
111
117
  configurable: true,
@@ -338,7 +344,11 @@ class ScrapeConfig {
338
344
  this.cache = options.cache ?? this.cache;
339
345
  this.cache_clear = options.cache_clear ?? this.cache_clear;
340
346
  this.cost_budget = options.cost_budget ?? this.cost_budget;
341
- this.asp = options.asp ?? this.asp;
347
+ // `asp` is the deprecated alias of `unblocker` and an explicitly supplied
348
+ // `asp` always wins; `unblocker` applies only when `asp` was not supplied.
349
+ // `??` and not `||`, so an explicit `false` on either name turns the
350
+ // feature off instead of falling through to the other name.
351
+ this.asp = options.asp ?? options.unblocker ?? this.asp;
342
352
  this.headers = options.headers
343
353
  ? Object.fromEntries(Object.entries(options.headers).map(([k, v]) => [k.toLowerCase(), v]))
344
354
  : {};
@@ -403,10 +413,26 @@ class ScrapeConfig {
403
413
  }
404
414
  }
405
415
  }
416
+ /**
417
+ * Anti-bot bypass toggle — the current name for what used to be `asp`.
418
+ *
419
+ * An accessor over the single `asp` field rather than a second stored
420
+ * property: one storage slot means the two names can never disagree, so
421
+ * `config.unblocker = true` after construction is exactly `config.asp = true`
422
+ * and `toApiParams` has one value to read. It also keeps `unblocker` out of
423
+ * the instance's own keys, so serializers that iterate them do not sprout a
424
+ * duplicate of `asp`.
425
+ */
426
+ get unblocker() {
427
+ return this.asp;
428
+ }
429
+ set unblocker(value) {
430
+ this.asp = value;
431
+ }
406
432
  validateOptions(options) {
407
433
  const validKeys = new Set(Object.keys(this));
408
434
  for (const key in options) {
409
- if (!validKeys.has(key)) {
435
+ if (!validKeys.has(key) && !ScrapeConfig.ALIAS_OPTION_KEYS.has(key)) {
410
436
  throw new errors_js_1.ScrapeConfigError(`Invalid option provided: ${key}`);
411
437
  }
412
438
  }
@@ -505,6 +531,11 @@ class ScrapeConfig {
505
531
  logger_js_1.log.warn('Params "rendering_wait" is ignored. Works only if render_js is enabled');
506
532
  }
507
533
  }
534
+ // The wire key stays `asp` for both names. A published package version is
535
+ // immutable and upgraded per installation, so emitting `unblocker` against
536
+ // an API deployment that has not learned that name yet would silently drop
537
+ // a paid feature: the scrape succeeds, is billed, and returns a blocked
538
+ // page. Renaming the emitted key is a separate, later release.
508
539
  if (this.asp === true) {
509
540
  params.asp = true;
510
541
  }
@@ -607,3 +638,14 @@ Object.defineProperty(ScrapeConfig, "PUBLIC_TOR_POOL", {
607
638
  writable: true,
608
639
  value: 'public_tor_pool'
609
640
  });
641
+ /**
642
+ * Option names the constructor accepts that are not own properties of the
643
+ * instance. `unblocker` is an accessor, so it lives on the prototype and the
644
+ * `Object.keys(this)` allow-list below never sees it.
645
+ */
646
+ Object.defineProperty(ScrapeConfig, "ALIAS_OPTION_KEYS", {
647
+ enumerable: true,
648
+ configurable: true,
649
+ writable: true,
650
+ value: new Set(['unblocker'])
651
+ });
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AACvC,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;AAYnE,kEAAkE;AAClE,MAAM,MAAM,KAAK,GAAG;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACtB,CAAC;AAEF,mEAAmE;AACnE,MAAM,MAAM,aAAa,GAAG,UAAU,GAAG,SAAS,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEvE;;;;;;GAMG;AACH,MAAM,MAAM,WAAW,GAAG;IAExB,QAAQ,CAAC,EAAE,MAAM,GAAG;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IAEzC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB,OAAO,CAAC,EAAE;QACR,YAAY,EAAE,MAAM,CAAC;QACrB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AAC,CAAC;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACtB,CAAC;AAEF,yDAAyD;AACzD,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,aAAa,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,WAAW,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,CAAC"}
@@ -1,36 +1,54 @@
1
1
  import { Buffer } from 'node:buffer';
2
+ /**
3
+ * Values Scrapfly sends in the `X-Scrapfly-Webhook-Resource-Type` header.
4
+ *
5
+ * ALERT is signed over `<timestamp>.<body>` rather than over the body, and so
6
+ * is verified through a separate path.
7
+ */
2
8
  export declare enum ResourceType {
3
9
  SCRAPE = "scrape",
4
- PING = "ping"
10
+ PING = "ping",
11
+ CRAWL = "crawl",
12
+ EXTRACTION = "extraction",
13
+ SCREENSHOT = "screenshot",
14
+ ALERT = "alert"
5
15
  }
6
16
  /**
7
17
  * Verify that a webhook request was sent by Scrapfly by comparing the
8
18
  * HMAC-SHA256 signature on the request body against the configured
9
19
  * signing secret.
10
20
  *
11
- * @param body Raw request body as received (verify BEFORE any decompression
12
- * or JSON parsing — the signature is computed on the bytes
13
- * Scrapfly sent on the wire).
21
+ * @param body Body as Scrapfly signed it: decompressed, but not JSON-parsed.
22
+ * Signing happens before `Content-Encoding` is applied, so a
23
+ * compressed request must be inflated first.
14
24
  * @param signature Value of the `X-Scrapfly-Webhook-Signature` header
15
- * (uppercase hex digest).
16
- * @param signingSecret Webhook signing secret from the dashboard, passed as-is
17
- * (UTF-8 string; not hex-encoded).
25
+ * (uppercase hex digest). The `-Lowercase` header carries
26
+ * the same digest and is accepted too.
27
+ * @param signingSecret Webhook signing secret, passed as-is (UTF-8 string; not
28
+ * hex-encoded). Pass an array to accept any of several
29
+ * secrets, for key rotation.
18
30
  * @returns `true` if the signature matches.
19
31
  */
20
- export declare function verifySignature(body: Buffer, signature: string, signingSecret: string): boolean;
32
+ export declare function verifySignature(body: Buffer, signature: string | undefined | null, signingSecret: string | string[]): boolean;
21
33
  /**
22
- * Start a tiny Express server that receives Scrapfly webhook callbacks
23
- * and dispatches them to the provided `callback`. Intended for quick
24
- * integration and local development; production setups should wire
25
- * Scrapfly webhooks directly into their own HTTP stack via
34
+ * Start a tiny Express server that receives Scrapfly webhook callbacks,
35
+ * verifies their signature, and dispatches them to the provided `callback`.
36
+ * Intended for quick integration and local development; production setups
37
+ * should wire Scrapfly webhooks directly into their own HTTP stack via
26
38
  * {@link verifySignature}.
27
39
  *
40
+ * Every request must be signed. A body with no `X-Scrapfly-Webhook-Signature`
41
+ * is rejected with 401 rather than delivered.
42
+ *
28
43
  * Requires the `express` package to be installed.
29
44
  *
30
- * @param callback Invoked with the parsed webhook body, its resource
31
- * type (`scrape` or `ping`), and the raw Express request.
45
+ * @param signingSecrets Webhook signing secret(s) from your webhook settings.
46
+ * @param callback Invoked with the verified body, its resource type, and the
47
+ * raw Express request. Awaited, so an async callback's failure yields 500. Bodies are JSON-parsed when the content type says so;
48
+ * binary payloads (screenshot images) arrive as a Buffer.
32
49
  * @param app Optional pre-configured Express app to mount on.
50
+ * @param maxBodyBytes Reject bodies larger than this, before any decompression.
33
51
  * @returns The underlying Express app (for further configuration or `.listen()`).
34
52
  */
35
- export declare function createServer(callback: (data: any, resourceType: string, request: any) => void, app?: any): Promise<any>;
53
+ export declare function createServer(signingSecrets: string | string[], callback: (data: any, resourceType: string, request: any) => void | Promise<void>, app?: any, maxBodyBytes?: number): Promise<any>;
36
54
  //# sourceMappingURL=webhookserver.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"webhookserver.d.ts","sourceRoot":"","sources":["../src/webhookserver.ts"],"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AC,GAAG,CAAC,CAwFd"}
@@ -31,51 +31,173 @@ exports.verifySignature = verifySignature;
31
31
  exports.createServer = createServer;
32
32
  const node_buffer_1 = require("node:buffer");
33
33
  const node_crypto_1 = __importDefault(require("node:crypto"));
34
+ const node_zlib_1 = __importDefault(require("node:zlib"));
34
35
  const logger_js_1 = require("./logger.js");
36
+ /**
37
+ * Values Scrapfly sends in the `X-Scrapfly-Webhook-Resource-Type` header.
38
+ *
39
+ * ALERT is signed over `<timestamp>.<body>` rather than over the body, and so
40
+ * is verified through a separate path.
41
+ */
35
42
  var ResourceType;
36
43
  (function (ResourceType) {
37
44
  ResourceType["SCRAPE"] = "scrape";
38
45
  ResourceType["PING"] = "ping";
46
+ ResourceType["CRAWL"] = "crawl";
47
+ ResourceType["EXTRACTION"] = "extraction";
48
+ ResourceType["SCREENSHOT"] = "screenshot";
49
+ ResourceType["ALERT"] = "alert";
39
50
  })(ResourceType || (exports.ResourceType = ResourceType = {}));
51
+ /** Replay window for alert webhooks, applied either side of now to tolerate clock skew. */
52
+ const ALERT_TIMESTAMP_TOLERANCE_SECONDS = 300;
53
+ /**
54
+ * Rebuild the `<timestamp>.<body>` message an alert webhook is signed over, or
55
+ * return null when the timestamp is absent, unparseable, or outside the replay
56
+ * window.
57
+ */
58
+ function alertSignedMessage(timestamp, body, tolerance = ALERT_TIMESTAMP_TOLERANCE_SECONDS) {
59
+ if (!timestamp || !/^\d+$/.test(timestamp)) {
60
+ return null;
61
+ }
62
+ if (Math.abs(Date.now() / 1000 - Number(timestamp)) > tolerance) {
63
+ return null;
64
+ }
65
+ return node_buffer_1.Buffer.concat([node_buffer_1.Buffer.from(`${timestamp}.`, 'utf8'), body]);
66
+ }
67
+ const RESOURCE_TYPES = Object.values(ResourceType);
68
+ /**
69
+ * The signature covers the decompressed bytes, so decompression runs before the
70
+ * request is authenticated and needs its own ceiling.
71
+ */
72
+ const MAX_BODY_BYTES = 256 * 1024 * 1024;
40
73
  /**
41
74
  * Verify that a webhook request was sent by Scrapfly by comparing the
42
75
  * HMAC-SHA256 signature on the request body against the configured
43
76
  * signing secret.
44
77
  *
45
- * @param body Raw request body as received (verify BEFORE any decompression
46
- * or JSON parsing — the signature is computed on the bytes
47
- * Scrapfly sent on the wire).
78
+ * @param body Body as Scrapfly signed it: decompressed, but not JSON-parsed.
79
+ * Signing happens before `Content-Encoding` is applied, so a
80
+ * compressed request must be inflated first.
48
81
  * @param signature Value of the `X-Scrapfly-Webhook-Signature` header
49
- * (uppercase hex digest).
50
- * @param signingSecret Webhook signing secret from the dashboard, passed as-is
51
- * (UTF-8 string; not hex-encoded).
82
+ * (uppercase hex digest). The `-Lowercase` header carries
83
+ * the same digest and is accepted too.
84
+ * @param signingSecret Webhook signing secret, passed as-is (UTF-8 string; not
85
+ * hex-encoded). Pass an array to accept any of several
86
+ * secrets, for key rotation.
52
87
  * @returns `true` if the signature matches.
53
88
  */
54
89
  function verifySignature(body, signature, signingSecret) {
55
- const hmac = node_crypto_1.default.createHmac('sha256', node_buffer_1.Buffer.from(signingSecret, 'utf8'));
56
- hmac.update(body);
57
- const computed = hmac.digest('hex').toUpperCase();
58
- const received = signature.toUpperCase();
59
- if (computed.length !== received.length) {
90
+ const secrets = (Array.isArray(signingSecret) ? signingSecret : [signingSecret]).filter(Boolean);
91
+ // An empty key is a usable HMAC key: verifying against one accepts a digest
92
+ // anybody can compute.
93
+ if (secrets.length === 0) {
94
+ throw new Error('verifySignature requires a non-empty signing secret');
95
+ }
96
+ if (!signature) {
60
97
  return false;
61
98
  }
62
- return node_crypto_1.default.timingSafeEqual(node_buffer_1.Buffer.from(computed), node_buffer_1.Buffer.from(received));
99
+ const received = node_buffer_1.Buffer.from(signature.trim().toUpperCase(), 'utf8');
100
+ return secrets.some((secret) => {
101
+ const hmac = node_crypto_1.default.createHmac('sha256', node_buffer_1.Buffer.from(secret, 'utf8'));
102
+ hmac.update(body);
103
+ const computed = node_buffer_1.Buffer.from(hmac.digest('hex').toUpperCase(), 'utf8');
104
+ // timingSafeEqual throws on a length mismatch; hex digests are fixed-width.
105
+ if (computed.length !== received.length) {
106
+ return false;
107
+ }
108
+ return node_crypto_1.default.timingSafeEqual(computed, received);
109
+ });
110
+ }
111
+ /**
112
+ * Reverse the `Content-Encoding` applied to a webhook body.
113
+ */
114
+ function decompress(body, contentEncoding, limit) {
115
+ // maxOutputLength aborts mid-inflate; without it the ceiling is buffer.kMaxLength.
116
+ const options = { maxOutputLength: limit };
117
+ switch ((contentEncoding || '').toLowerCase()) {
118
+ case '':
119
+ case 'none':
120
+ case 'identity':
121
+ return body;
122
+ case 'gzip':
123
+ case 'gz':
124
+ return node_zlib_1.default.gunzipSync(body, options);
125
+ case 'deflate':
126
+ return node_zlib_1.default.inflateSync(body, options);
127
+ case 'br':
128
+ case 'brotli':
129
+ return node_zlib_1.default.brotliDecompressSync(body, options);
130
+ case 'zstd': {
131
+ const zstdDecompressSync = node_zlib_1.default.zstdDecompressSync;
132
+ if (typeof zstdDecompressSync !== 'function') {
133
+ throw new Error('zstd webhook bodies require Node 22+; set the webhook content encoding to gzip or none');
134
+ }
135
+ return zstdDecompressSync(body, options);
136
+ }
137
+ default:
138
+ throw new Error(`Unsupported webhook content encoding: ${contentEncoding}`);
139
+ }
140
+ }
141
+ /** Raised when a body is larger than the configured cap, before or after inflation. */
142
+ class WebhookBodyTooLarge extends Error {
143
+ }
144
+ /**
145
+ * Collect the request body without a body parser in front of it. body-parser
146
+ * answers 415 for any encoding it cannot inflate itself, and hands back a
147
+ * parsed object where the signature needs bytes.
148
+ */
149
+ function readBody(req, limit) {
150
+ // express.raw() leaves the bytes on req.body.
151
+ if (node_buffer_1.Buffer.isBuffer(req.body)) {
152
+ return Promise.resolve(req.body);
153
+ }
154
+ // An object-producing parser (express.json()) already drained the stream, so
155
+ // 'data' and 'end' never fire again and awaiting them parks the request until the
156
+ // socket times out. Its output is unusable here: the signature covers bytes.
157
+ if (req.readableEnded || req.complete) {
158
+ return Promise.reject(new Error('the request body was already consumed by another body parser. Mount the Scrapfly ' +
159
+ 'webhook route on an app without a global express.json()/urlencoded(), or register ' +
160
+ 'those parsers after createServer(), so the raw bytes reach signature verification.'));
161
+ }
162
+ return new Promise((resolve, reject) => {
163
+ const chunks = [];
164
+ let size = 0;
165
+ req.on('data', (chunk) => {
166
+ size += chunk.length;
167
+ if (size > limit) {
168
+ reject(new WebhookBodyTooLarge(`webhook body exceeds ${limit} bytes`));
169
+ return;
170
+ }
171
+ chunks.push(chunk);
172
+ });
173
+ req.on('end', () => resolve(node_buffer_1.Buffer.concat(chunks)));
174
+ req.on('error', reject);
175
+ });
63
176
  }
64
177
  /**
65
- * Start a tiny Express server that receives Scrapfly webhook callbacks
66
- * and dispatches them to the provided `callback`. Intended for quick
67
- * integration and local development; production setups should wire
68
- * Scrapfly webhooks directly into their own HTTP stack via
178
+ * Start a tiny Express server that receives Scrapfly webhook callbacks,
179
+ * verifies their signature, and dispatches them to the provided `callback`.
180
+ * Intended for quick integration and local development; production setups
181
+ * should wire Scrapfly webhooks directly into their own HTTP stack via
69
182
  * {@link verifySignature}.
70
183
  *
184
+ * Every request must be signed. A body with no `X-Scrapfly-Webhook-Signature`
185
+ * is rejected with 401 rather than delivered.
186
+ *
71
187
  * Requires the `express` package to be installed.
72
188
  *
73
- * @param callback Invoked with the parsed webhook body, its resource
74
- * type (`scrape` or `ping`), and the raw Express request.
189
+ * @param signingSecrets Webhook signing secret(s) from your webhook settings.
190
+ * @param callback Invoked with the verified body, its resource type, and the
191
+ * raw Express request. Awaited, so an async callback's failure yields 500. Bodies are JSON-parsed when the content type says so;
192
+ * binary payloads (screenshot images) arrive as a Buffer.
75
193
  * @param app Optional pre-configured Express app to mount on.
194
+ * @param maxBodyBytes Reject bodies larger than this, before any decompression.
76
195
  * @returns The underlying Express app (for further configuration or `.listen()`).
77
196
  */
78
- async function createServer(callback, app) {
197
+ async function createServer(signingSecrets, callback, app, maxBodyBytes = MAX_BODY_BYTES) {
198
+ if (!signingSecrets || (Array.isArray(signingSecrets) && signingSecrets.length === 0)) {
199
+ throw new Error('createServer requires the webhook signing secret(s) from your Scrapfly dashboard');
200
+ }
79
201
  let express;
80
202
  try {
81
203
  const expressModule = await Promise.resolve().then(() => __importStar(require('express')));
@@ -87,31 +209,68 @@ async function createServer(callback, app) {
87
209
  if (!app) {
88
210
  app = express();
89
211
  }
90
- const jsonMiddleware = express.json({
91
- verify: (req, _res, buf) => {
92
- req.rawBody = buf;
93
- },
94
- });
95
- app.post('/webhook', jsonMiddleware, (req, res) => {
212
+ app.post('/webhook', async (req, res) => {
213
+ const resourceType = req.headers['x-scrapfly-webhook-resource-type'];
214
+ // The digest is sent under both spellings; accept either.
215
+ const signature = req.headers['x-scrapfly-webhook-signature'] ||
216
+ req.headers['x-scrapfly-webhook-signature-lowercase'];
217
+ if (!RESOURCE_TYPES.includes(resourceType)) {
218
+ // Attacker-controlled and served as text/html: never echo it back.
219
+ logger_js_1.log.error('Unsupported resource type:', JSON.stringify(resourceType));
220
+ return res.status(400).send('unsupported resource type');
221
+ }
222
+ // A ping sent while a webhook is being created carries no signature. Answer the
223
+ // reachability probe, but never hand an unverified body to the callback: the
224
+ // resource type is as unauthenticated as the signature.
225
+ if (resourceType === ResourceType.PING && !signature) {
226
+ return res.status(200).send('');
227
+ }
228
+ let body;
96
229
  try {
97
- const resourceType = req.headers['x-scrapfly-webhook-resource-type'];
98
- if (resourceType !== 'scrape' && resourceType !== 'ping') {
99
- logger_js_1.log.error(`Unsupported resource type: ${resourceType}`);
100
- return res.status(400).send(`this webhook server only supports scrape and ping calls`);
230
+ body = decompress(await readBody(req, maxBodyBytes), req.headers['content-encoding'], maxBodyBytes);
231
+ }
232
+ catch (e) {
233
+ logger_js_1.log.error('Webhook decoding error:', e);
234
+ // Decoding runs before verification, so these failures are reachable unauthenticated.
235
+ return res.status(e instanceof WebhookBodyTooLarge ? 413 : 400).send('');
236
+ }
237
+ let signedMessage = body;
238
+ if (resourceType === ResourceType.ALERT) {
239
+ signedMessage = alertSignedMessage(req.headers['x-scrapfly-webhook-timestamp'], body);
240
+ if (signedMessage === null) {
241
+ logger_js_1.log.error(`Rejected alert webhook with a missing or stale timestamp from ${req.ip}`);
242
+ return res.status(401).send('');
101
243
  }
102
- const data = req.body;
103
- try {
104
- callback(data, resourceType, req);
105
- res.status(200).send('');
244
+ }
245
+ if (!verifySignature(signedMessage, signature, signingSecrets)) {
246
+ logger_js_1.log.error(`Rejected unsigned or mis-signed ${resourceType} webhook from ${req.ip}`);
247
+ return res.status(401).send('');
248
+ }
249
+ let data = body;
250
+ const contentType = (req.headers['content-type'] || '');
251
+ try {
252
+ if (contentType.startsWith('application/json')) {
253
+ data = JSON.parse(body.toString('utf8'));
106
254
  }
107
- catch (e) {
108
- logger_js_1.log.error('Callback error:', e);
109
- res.status(500).send('');
255
+ else if (contentType.startsWith('application/msgpack')) {
256
+ // application/msgpack is an offered webhook content type.
257
+ const { decode } = await Promise.resolve().then(() => __importStar(require('@msgpack/msgpack')));
258
+ data = decode(body);
110
259
  }
111
260
  }
112
261
  catch (e) {
113
- logger_js_1.log.error('Webhook processing error:', e);
114
- res.status(400).send('');
262
+ logger_js_1.log.error('Webhook body parse error:', e);
263
+ return res.status(400).send('');
264
+ }
265
+ try {
266
+ // Awaited: an un-awaited async callback rejects into an unhandled rejection,
267
+ // which terminates the process on Node >= 15.
268
+ await callback(data, resourceType, req);
269
+ return res.status(200).send('');
270
+ }
271
+ catch (e) {
272
+ logger_js_1.log.error('Callback error:', e);
273
+ return res.status(500).send('');
115
274
  }
116
275
  });
117
276
  return app;
@@ -14,6 +14,12 @@ export enum OperatingSystem {
14
14
  WINDOWS = 'windows',
15
15
  /** Emulate a macOS browser fingerprint. */
16
16
  MACOS = 'macos',
17
+ /** Emulate an Android phone browser fingerprint. */
18
+ ANDROID = 'android',
19
+ /** Emulate an iPhone browser fingerprint. */
20
+ IPHONE = 'iphone',
21
+ /** Emulate an iPad browser fingerprint. */
22
+ IPAD = 'ipad',
17
23
  }
18
24
 
19
25
  /**
@@ -30,6 +36,18 @@ export type BrowserConfigOptions = {
30
36
  session?: string;
31
37
  /** ISO country code for geo-targeting. */
32
38
  country?: string;
39
+ /**
40
+ * Browser UI language — the singular `navigator.language` base tag
41
+ * (e.g. "en"). When omitted, the server derives it from `country`.
42
+ */
43
+ lang?: string;
44
+ /**
45
+ * Ordered language preference list driving `navigator.languages` and the
46
+ * q-weighted `Accept-Language` header (e.g. ["fr-FR", "fr", "en-US"]).
47
+ * Pass a comma-separated string or an array; capped server-side at 3
48
+ * entries.
49
+ */
50
+ languages?: string | string[];
33
51
  /** Close the browser automatically when the connection drops. */
34
52
  auto_close?: boolean;
35
53
  /** Session timeout in seconds (max 1800 = 30 minutes). */
@@ -65,7 +83,7 @@ export type BrowserConfigOptions = {
65
83
  /** Enable the MCP (Model Context Protocol) bridge. */
66
84
  enable_mcp?: boolean;
67
85
  /**
68
- * Arm Scrapium's built-in captcha detector + solver on the first page attach.
86
+ * Arm the Cloud Browser's built-in captcha detector + solver on the first page attach.
69
87
  * Turnstile, DataDome slider, reCAPTCHA, GeeTest, PerimeterX hold, and
70
88
  * puzzle captchas are handled automatically — no extra CDP calls from the
71
89
  * client. Billed per solve; failures cost nothing.
@@ -117,6 +135,10 @@ export class BrowserConfig {
117
135
  session?: string;
118
136
  /** See {@link BrowserConfigOptions.country}. */
119
137
  country?: string;
138
+ /** See {@link BrowserConfigOptions.lang}. */
139
+ lang?: string;
140
+ /** See {@link BrowserConfigOptions.languages}. Normalized to a comma-separated string. */
141
+ languages?: string;
120
142
  /** See {@link BrowserConfigOptions.auto_close}. */
121
143
  auto_close?: boolean;
122
144
  /** See {@link BrowserConfigOptions.timeout}. */
@@ -182,6 +204,13 @@ export class BrowserConfig {
182
204
  this.os = options.os;
183
205
  this.session = options.session;
184
206
  this.country = options.country;
207
+ this.lang = options.lang;
208
+ if (Array.isArray(options.languages)) {
209
+ const cleaned = options.languages.map((s) => s.trim()).filter((s) => s.length > 0);
210
+ this.languages = cleaned.length > 0 ? cleaned.join(',') : undefined;
211
+ } else {
212
+ this.languages = options.languages || undefined;
213
+ }
185
214
  this.auto_close = options.auto_close;
186
215
  this.timeout = options.timeout;
187
216
  this.debug = options.debug;
@@ -219,9 +248,10 @@ export class BrowserConfig {
219
248
 
220
249
  /**
221
250
  * Return the deterministic project salt for an api_key (`sha256(api_key)[:8]`).
222
- * Matches the `X-Browser-Project-Salt` response header returned on a
223
- * successful Cloud Browser WebSocket upgrade. Useful for verifying that
224
- * an attach link belongs to your project before sharing it.
251
+ * Matches the `X-Browser-Project-Salt` response header returned on
252
+ * VNC-enabled Cloud Browser upgrades, where the salt is also the VNC
253
+ * password prefix. Useful for verifying that an attach link belongs to
254
+ * your project before sharing it.
225
255
  *
226
256
  * Uses the Web Crypto API where available (modern Node and browsers).
227
257
  */
@@ -236,6 +266,22 @@ export class BrowserConfig {
236
266
  return hex;
237
267
  }
238
268
 
269
+ /**
270
+ * Return the password a native VNC client must type to attach to a session
271
+ * created with this config: `<projectSalt>-<vnc_password>`.
272
+ *
273
+ * Required by the VNC TCP endpoint (port 5901), which the server salts at
274
+ * allocation. The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
275
+ * `vnc_password` instead.
276
+ */
277
+ async vncClientPassword(apiKey: string): Promise<string> {
278
+ if (!this.enable_vnc || !this.vnc_password) {
279
+ throw new Error('enable_vnc and vnc_password must both be set on this BrowserConfig');
280
+ }
281
+ const salt = await BrowserConfig.projectSalt(apiKey);
282
+ return `${salt}-${this.vnc_password}`;
283
+ }
284
+
239
285
  /**
240
286
  * Build the WebSocket URL clients use to connect to the Cloud Browser
241
287
  * session (compatible with Puppeteer `browserWSEndpoint` and the
@@ -253,6 +299,8 @@ export class BrowserConfig {
253
299
  if (this.os !== undefined) params.set('os', this.os);
254
300
  if (this.session !== undefined) params.set('session', this.session);
255
301
  if (this.country !== undefined) params.set('country', this.country);
302
+ if (this.lang !== undefined) params.set('lang', this.lang);
303
+ if (this.languages !== undefined) params.set('languages', this.languages);
256
304
  if (this.auto_close !== undefined) params.set('auto_close', String(this.auto_close));
257
305
  if (this.timeout !== undefined) params.set('timeout', String(this.timeout));
258
306
  if (this.debug !== undefined) params.set('debug', String(this.debug));