scrapfly-sdk 0.11.1 → 0.12.1

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 (101) hide show
  1. package/README.md +72 -5
  2. package/esm/browserconfig.d.ts +57 -9
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +63 -5
  5. package/esm/browserdownloads.d.ts +70 -0
  6. package/esm/browserdownloads.d.ts.map +1 -0
  7. package/esm/browserdownloads.js +215 -0
  8. package/esm/client.d.ts +224 -8
  9. package/esm/client.d.ts.map +1 -1
  10. package/esm/client.js +646 -62
  11. package/esm/crawl.d.ts +83 -1
  12. package/esm/crawl.d.ts.map +1 -1
  13. package/esm/crawl.js +73 -0
  14. package/esm/crawlerconfig.d.ts +54 -3
  15. package/esm/crawlerconfig.d.ts.map +1 -1
  16. package/esm/crawlerconfig.js +96 -2
  17. package/esm/crawlerresult.d.ts +374 -2
  18. package/esm/crawlerresult.d.ts.map +1 -1
  19. package/esm/crawlerresult.js +367 -1
  20. package/esm/errors.d.ts +12 -0
  21. package/esm/errors.d.ts.map +1 -1
  22. package/esm/errors.js +11 -0
  23. package/esm/main.d.ts +12 -7
  24. package/esm/main.d.ts.map +1 -1
  25. package/esm/main.js +10 -5
  26. package/esm/monitoringconfig.d.ts +2 -2
  27. package/esm/result.d.ts +11 -1
  28. package/esm/result.d.ts.map +1 -1
  29. package/esm/result.js +14 -5
  30. package/esm/scrapeconfig.d.ts +65 -1
  31. package/esm/scrapeconfig.d.ts.map +1 -1
  32. package/esm/scrapeconfig.js +88 -4
  33. package/esm/screenshotconfig.d.ts +9 -1
  34. package/esm/screenshotconfig.d.ts.map +1 -1
  35. package/esm/screenshotconfig.js +12 -1
  36. package/esm/types.d.ts +128 -0
  37. package/esm/types.d.ts.map +1 -1
  38. package/esm/types.js +22 -1
  39. package/esm/utils.d.ts.map +1 -1
  40. package/esm/utils.js +16 -2
  41. package/esm/webhookserver.d.ts +33 -15
  42. package/esm/webhookserver.d.ts.map +1 -1
  43. package/esm/webhookserver.js +197 -38
  44. package/package.json +1 -1
  45. package/script/browserconfig.d.ts +57 -9
  46. package/script/browserconfig.d.ts.map +1 -1
  47. package/script/browserconfig.js +63 -5
  48. package/script/browserdownloads.d.ts +70 -0
  49. package/script/browserdownloads.d.ts.map +1 -0
  50. package/script/browserdownloads.js +221 -0
  51. package/script/client.d.ts +224 -8
  52. package/script/client.d.ts.map +1 -1
  53. package/script/client.js +645 -61
  54. package/script/crawl.d.ts +83 -1
  55. package/script/crawl.d.ts.map +1 -1
  56. package/script/crawl.js +73 -0
  57. package/script/crawlerconfig.d.ts +54 -3
  58. package/script/crawlerconfig.d.ts.map +1 -1
  59. package/script/crawlerconfig.js +97 -3
  60. package/script/crawlerresult.d.ts +374 -2
  61. package/script/crawlerresult.d.ts.map +1 -1
  62. package/script/crawlerresult.js +374 -2
  63. package/script/errors.d.ts +12 -0
  64. package/script/errors.d.ts.map +1 -1
  65. package/script/errors.js +12 -1
  66. package/script/main.d.ts +12 -7
  67. package/script/main.d.ts.map +1 -1
  68. package/script/main.js +20 -4
  69. package/script/monitoringconfig.d.ts +2 -2
  70. package/script/result.d.ts +11 -1
  71. package/script/result.d.ts.map +1 -1
  72. package/script/result.js +14 -5
  73. package/script/scrapeconfig.d.ts +65 -1
  74. package/script/scrapeconfig.d.ts.map +1 -1
  75. package/script/scrapeconfig.js +88 -4
  76. package/script/screenshotconfig.d.ts +9 -1
  77. package/script/screenshotconfig.d.ts.map +1 -1
  78. package/script/screenshotconfig.js +12 -1
  79. package/script/types.d.ts +128 -0
  80. package/script/types.d.ts.map +1 -1
  81. package/script/types.js +23 -0
  82. package/script/utils.d.ts.map +1 -1
  83. package/script/utils.js +16 -2
  84. package/script/webhookserver.d.ts +33 -15
  85. package/script/webhookserver.d.ts.map +1 -1
  86. package/script/webhookserver.js +197 -38
  87. package/src/browserconfig.ts +74 -8
  88. package/src/browserdownloads.ts +266 -0
  89. package/src/client.ts +796 -65
  90. package/src/crawl.ts +106 -0
  91. package/src/crawlerconfig.ts +128 -5
  92. package/src/crawlerresult.ts +607 -3
  93. package/src/errors.ts +12 -0
  94. package/src/main.ts +55 -5
  95. package/src/monitoringconfig.ts +2 -2
  96. package/src/result.ts +17 -5
  97. package/src/scrapeconfig.ts +92 -3
  98. package/src/screenshotconfig.ts +14 -1
  99. package/src/types.ts +159 -1
  100. package/src/utils.ts +16 -2
  101. package/src/webhookserver.ts +235 -39
package/script/utils.js CHANGED
@@ -13,6 +13,18 @@ function urlsafe_b64encode(data) {
13
13
  .replace(/=+$/, '');
14
14
  return base64;
15
15
  }
16
+ const KEY_IN_URL = /(?<=[?&]key=)[^&\s)'"]+/g;
17
+ /**
18
+ * Mask the API key in a fetch error, in place: Deno prints the request URL,
19
+ * query and key included, in the message and in the stack it captured.
20
+ */
21
+ function maskKey(error) {
22
+ if (!(error instanceof Error))
23
+ return;
24
+ error.message = error.message.replace(KEY_IN_URL, 'REDACTED');
25
+ if (error.stack !== undefined)
26
+ error.stack = error.stack.replace(KEY_IN_URL, 'REDACTED');
27
+ }
16
28
  async function fetchRetry(config, retries = 3, retryDelay = 1000) {
17
29
  let lastError = null;
18
30
  for (let attempt = 1; attempt <= retries; attempt++) {
@@ -31,8 +43,9 @@ async function fetchRetry(config, retries = 3, retryDelay = 1000) {
31
43
  body: reqInit.body,
32
44
  };
33
45
  const response = await fetch(new Request(url, init));
34
- // retry 5xx status codes
35
- if (response.status >= 500 && response.status < 600) {
46
+ // Retry 5xx status codes. A single-attempt caller reads the 5xx body
47
+ // itself: it carries the typed error.
48
+ if (response.status >= 500 && response.status < 600 && retries > 1) {
36
49
  const _text = await response.text(); // consume response to prevent leak
37
50
  lastError = new Error(`Fetch failed with status: ${response.status}`);
38
51
  if (attempt < retries) {
@@ -45,6 +58,7 @@ async function fetchRetry(config, retries = 3, retryDelay = 1000) {
45
58
  }
46
59
  }
47
60
  catch (error) {
61
+ maskKey(error);
48
62
  lastError = error;
49
63
  // AbortError should never be retried: it means the caller explicitly
50
64
  // gave up (cancel token, timeout, etc.) and we shouldn't paper over it.
@@ -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"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;CACd;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAS/F;AAGD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,EACjE,GAAG,CAAC,EAAE,GAAG,GACR,OAAO,CAAC,GAAG,CAAC,CA4Cd"}
1
+ {"version":3,"file":"webhookserver.d.ts","sourceRoot":"","sources":["../src/webhookserver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC;;;;;GAKG;AACH,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;IACb,KAAK,UAAU;IACf,UAAU,eAAe;IACzB,UAAU,eAAe;IACzB,KAAK,UAAU;CAChB;AAkCD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,EACpC,aAAa,EAAE,MAAM,GAAG,MAAM,EAAE,GAC/B,OAAO,CA2BT;AAgFD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,YAAY,CAChC,cAAc,EAAE,MAAM,GAAG,MAAM,EAAE,EACjC,QAAQ,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,EACjF,GAAG,CAAC,EAAE,GAAG,EACT,YAAY,GAAE,MAAuB,GACpC,OAAO,CAAC,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). */
@@ -56,16 +74,24 @@ export type BrowserConfigOptions = {
56
74
  cache?: boolean;
57
75
  /** Apply Scrapfly's abuse blacklist. */
58
76
  blacklist?: boolean;
59
- /** Enable anti-scraping-protection bypass. */
77
+ /**
78
+ * @deprecated The Cloud Browser WebSocket endpoint does not read this
79
+ * parameter; it is sent but has no effect. Use
80
+ * {@link ScrapflyClient.cloudBrowserUnblock} (the `/unblock` endpoint).
81
+ */
60
82
  unblock?: boolean;
61
- /** Timeout in seconds for the unblock step. */
83
+ /**
84
+ * @deprecated The Cloud Browser WebSocket endpoint does not read this
85
+ * parameter; it is sent but has no effect. Use
86
+ * {@link ScrapflyClient.cloudBrowserUnblock}, which takes its own timeouts.
87
+ */
62
88
  unblock_timeout?: number;
63
89
  /** Browser brand to emulate (e.g. "chrome", "firefox"). */
64
90
  browser_brand?: string;
65
91
  /** Enable the MCP (Model Context Protocol) bridge. */
66
92
  enable_mcp?: boolean;
67
93
  /**
68
- * Arm Scrapium's built-in captcha detector + solver on the first page attach.
94
+ * Arm the Cloud Browser's built-in captcha detector + solver on the first page attach.
69
95
  * Turnstile, DataDome slider, reCAPTCHA, GeeTest, PerimeterX hold, and
70
96
  * puzzle captchas are handled automatically — no extra CDP calls from the
71
97
  * client. Billed per solve; failures cost nothing.
@@ -101,6 +127,12 @@ export type BrowserConfigOptions = {
101
127
  * comma-separated string or an array of bare IPs / CIDRs.
102
128
  */
103
129
  hitl_allowed_networks?: string | string[];
130
+ /**
131
+ * Return large downloaded files from `ScrapiumBrowser.getDownloads` as IO stream handles instead of
132
+ * inline base64: read them with `CloudBrowserDownloads`.
133
+ * See https://scrapfly.io/docs/cloud-browser-api/file-downloads#large-downloads
134
+ */
135
+ downloads_stream?: boolean;
104
136
  };
105
137
 
106
138
  /**
@@ -117,6 +149,10 @@ export class BrowserConfig {
117
149
  session?: string;
118
150
  /** See {@link BrowserConfigOptions.country}. */
119
151
  country?: string;
152
+ /** See {@link BrowserConfigOptions.lang}. */
153
+ lang?: string;
154
+ /** See {@link BrowserConfigOptions.languages}. Normalized to a comma-separated string. */
155
+ languages?: string;
120
156
  /** See {@link BrowserConfigOptions.auto_close}. */
121
157
  auto_close?: boolean;
122
158
  /** See {@link BrowserConfigOptions.timeout}. */
@@ -143,9 +179,9 @@ export class BrowserConfig {
143
179
  cache?: boolean;
144
180
  /** See {@link BrowserConfigOptions.blacklist}. */
145
181
  blacklist?: boolean;
146
- /** See {@link BrowserConfigOptions.unblock}. */
182
+ /** @deprecated Not read by the API, see {@link BrowserConfigOptions.unblock}. */
147
183
  unblock?: boolean;
148
- /** See {@link BrowserConfigOptions.unblock_timeout}. */
184
+ /** @deprecated Not read by the API, see {@link BrowserConfigOptions.unblock_timeout}. */
149
185
  unblock_timeout?: number;
150
186
  /** See {@link BrowserConfigOptions.browser_brand}. */
151
187
  browser_brand?: string;
@@ -169,6 +205,8 @@ export class BrowserConfig {
169
205
  rtc_password?: string;
170
206
  /** See {@link BrowserConfigOptions.hitl_allowed_networks}. */
171
207
  hitl_allowed_networks?: string;
208
+ /** See {@link BrowserConfigOptions.downloads_stream}. */
209
+ downloads_stream?: boolean;
172
210
 
173
211
  /**
174
212
  * @param options Session options. See {@link BrowserConfigOptions}.
@@ -182,6 +220,13 @@ export class BrowserConfig {
182
220
  this.os = options.os;
183
221
  this.session = options.session;
184
222
  this.country = options.country;
223
+ this.lang = options.lang;
224
+ if (Array.isArray(options.languages)) {
225
+ const cleaned = options.languages.map((s) => s.trim()).filter((s) => s.length > 0);
226
+ this.languages = cleaned.length > 0 ? cleaned.join(',') : undefined;
227
+ } else {
228
+ this.languages = options.languages || undefined;
229
+ }
185
230
  this.auto_close = options.auto_close;
186
231
  this.timeout = options.timeout;
187
232
  this.debug = options.debug;
@@ -215,13 +260,15 @@ export class BrowserConfig {
215
260
  } else {
216
261
  this.hitl_allowed_networks = options.hitl_allowed_networks || undefined;
217
262
  }
263
+ this.downloads_stream = options.downloads_stream;
218
264
  }
219
265
 
220
266
  /**
221
267
  * 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.
268
+ * Matches the `X-Browser-Project-Salt` response header returned on
269
+ * VNC-enabled Cloud Browser upgrades, where the salt is also the VNC
270
+ * password prefix. Useful for verifying that an attach link belongs to
271
+ * your project before sharing it.
225
272
  *
226
273
  * Uses the Web Crypto API where available (modern Node and browsers).
227
274
  */
@@ -236,6 +283,22 @@ export class BrowserConfig {
236
283
  return hex;
237
284
  }
238
285
 
286
+ /**
287
+ * Return the password a native VNC client must type to attach to a session
288
+ * created with this config: `<projectSalt>-<vnc_password>`.
289
+ *
290
+ * Required by the VNC TCP endpoint (port 5901), which the server salts at
291
+ * allocation. The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
292
+ * `vnc_password` instead.
293
+ */
294
+ async vncClientPassword(apiKey: string): Promise<string> {
295
+ if (!this.enable_vnc || !this.vnc_password) {
296
+ throw new Error('enable_vnc and vnc_password must both be set on this BrowserConfig');
297
+ }
298
+ const salt = await BrowserConfig.projectSalt(apiKey);
299
+ return `${salt}-${this.vnc_password}`;
300
+ }
301
+
239
302
  /**
240
303
  * Build the WebSocket URL clients use to connect to the Cloud Browser
241
304
  * session (compatible with Puppeteer `browserWSEndpoint` and the
@@ -253,6 +316,8 @@ export class BrowserConfig {
253
316
  if (this.os !== undefined) params.set('os', this.os);
254
317
  if (this.session !== undefined) params.set('session', this.session);
255
318
  if (this.country !== undefined) params.set('country', this.country);
319
+ if (this.lang !== undefined) params.set('lang', this.lang);
320
+ if (this.languages !== undefined) params.set('languages', this.languages);
256
321
  if (this.auto_close !== undefined) params.set('auto_close', String(this.auto_close));
257
322
  if (this.timeout !== undefined) params.set('timeout', String(this.timeout));
258
323
  if (this.debug !== undefined) params.set('debug', String(this.debug));
@@ -279,6 +344,7 @@ export class BrowserConfig {
279
344
  if (this.rtc_username !== undefined) params.set('rtc_username', this.rtc_username);
280
345
  if (this.rtc_password !== undefined) params.set('rtc_password', this.rtc_password);
281
346
  if (this.hitl_allowed_networks !== undefined) params.set('hitl_allowed_networks', this.hitl_allowed_networks);
347
+ if (this.downloads_stream !== undefined) params.set('downloads_stream', String(this.downloads_stream));
282
348
 
283
349
  const baseHost = host || 'wss://browser.scrapfly.io';
284
350
  return `${baseHost}?${params.toString()}`;