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
@@ -54,6 +54,18 @@ type ScrapeConfigOptions = {
54
54
  cost_budget?: number;
55
55
  ssl?: boolean;
56
56
  dns?: boolean;
57
+ /**
58
+ * Anti-bot bypass. The current name for what used to be called `asp`.
59
+ * Sent to the API as the `asp` query parameter; only the SDK-facing name
60
+ * changed.
61
+ */
62
+ unblocker?: boolean;
63
+ /**
64
+ * @deprecated Use {@link unblocker}. `asp` is a permanently supported alias
65
+ * and keeps working forever; only the documented name changed. When both are
66
+ * supplied `asp` wins, so existing code cannot have its meaning changed by a
67
+ * later `unblocker`.
68
+ */
57
69
  asp?: boolean;
58
70
  debug?: boolean;
59
71
  raise_on_upstream_error?: boolean;
@@ -125,6 +137,12 @@ export class ScrapeConfig {
125
137
  cost_budget?: number;
126
138
  ssl = false;
127
139
  dns = false;
140
+ /**
141
+ * Storage for the anti-bot bypass toggle, under its deprecated name.
142
+ * `unblocker` is an accessor over this same field — see below.
143
+ *
144
+ * @deprecated Use {@link ScrapeConfig.unblocker}. `asp` keeps working forever.
145
+ */
128
146
  asp = false;
129
147
  debug = false;
130
148
  raise_on_upstream_error = true;
@@ -190,7 +208,11 @@ export class ScrapeConfig {
190
208
  this.cache = options.cache ?? this.cache;
191
209
  this.cache_clear = options.cache_clear ?? this.cache_clear;
192
210
  this.cost_budget = options.cost_budget ?? this.cost_budget;
193
- this.asp = options.asp ?? this.asp;
211
+ // `asp` is the deprecated alias of `unblocker` and an explicitly supplied
212
+ // `asp` always wins; `unblocker` applies only when `asp` was not supplied.
213
+ // `??` and not `||`, so an explicit `false` on either name turns the
214
+ // feature off instead of falling through to the other name.
215
+ this.asp = options.asp ?? options.unblocker ?? this.asp;
194
216
  this.headers = options.headers
195
217
  ? Object.fromEntries(Object.entries(options.headers).map(([k, v]) => [k.toLowerCase(), v]))
196
218
  : {};
@@ -256,10 +278,35 @@ export class ScrapeConfig {
256
278
  }
257
279
  }
258
280
 
281
+ /**
282
+ * Anti-bot bypass toggle — the current name for what used to be `asp`.
283
+ *
284
+ * An accessor over the single `asp` field rather than a second stored
285
+ * property: one storage slot means the two names can never disagree, so
286
+ * `config.unblocker = true` after construction is exactly `config.asp = true`
287
+ * and `toApiParams` has one value to read. It also keeps `unblocker` out of
288
+ * the instance's own keys, so serializers that iterate them do not sprout a
289
+ * duplicate of `asp`.
290
+ */
291
+ get unblocker(): boolean {
292
+ return this.asp;
293
+ }
294
+
295
+ set unblocker(value: boolean) {
296
+ this.asp = value;
297
+ }
298
+
299
+ /**
300
+ * Option names the constructor accepts that are not own properties of the
301
+ * instance. `unblocker` is an accessor, so it lives on the prototype and the
302
+ * `Object.keys(this)` allow-list below never sees it.
303
+ */
304
+ private static readonly ALIAS_OPTION_KEYS: ReadonlySet<string> = new Set(['unblocker']);
305
+
259
306
  private validateOptions(options: Partial<ScrapeConfigOptions>) {
260
307
  const validKeys = new Set(Object.keys(this) as Array<keyof ScrapeConfig>);
261
308
  for (const key in options) {
262
- if (!validKeys.has(key as keyof ScrapeConfig)) {
309
+ if (!validKeys.has(key as keyof ScrapeConfig) && !ScrapeConfig.ALIAS_OPTION_KEYS.has(key)) {
263
310
  throw new ScrapeConfigError(`Invalid option provided: ${key}`);
264
311
  }
265
312
  }
@@ -359,6 +406,11 @@ export class ScrapeConfig {
359
406
  }
360
407
  }
361
408
 
409
+ // The wire key stays `asp` for both names. A published package version is
410
+ // immutable and upgraded per installation, so emitting `unblocker` against
411
+ // an API deployment that has not learned that name yet would silently drop
412
+ // a paid feature: the scrape succeeds, is billed, and returns a blocked
413
+ // page. Renaming the emitted key is a separate, later release.
362
414
  if (this.asp === true) {
363
415
  params.asp = true;
364
416
  }
package/src/types.ts CHANGED
@@ -8,7 +8,6 @@ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD';
8
8
  // encrypted server-side under a customer-held vault key. The server emits the
9
9
  // raw vault key exactly once on POST /vault and POST /vault/{id}/rotate; the
10
10
  // SDK MUST never log, print, or include it in error messages.
11
- // See compliance memory at agent_secret_tokenization_boundary.md.
12
11
  // ---------------------------------------------------------------------------
13
12
 
14
13
  /** Vault metadata returned by the server (no secret material). */
@@ -1,56 +1,212 @@
1
1
  import { Buffer } from 'node:buffer';
2
2
  import crypto from 'node:crypto';
3
+ import zlib from 'node:zlib';
3
4
  import { log } from './logger.js';
4
5
 
6
+ /**
7
+ * Values Scrapfly sends in the `X-Scrapfly-Webhook-Resource-Type` header.
8
+ *
9
+ * ALERT is signed over `<timestamp>.<body>` rather than over the body, and so
10
+ * is verified through a separate path.
11
+ */
5
12
  export enum ResourceType {
6
13
  SCRAPE = 'scrape',
7
14
  PING = 'ping',
15
+ CRAWL = 'crawl',
16
+ EXTRACTION = 'extraction',
17
+ SCREENSHOT = 'screenshot',
18
+ ALERT = 'alert',
8
19
  }
9
20
 
21
+ /** Replay window for alert webhooks, applied either side of now to tolerate clock skew. */
22
+ const ALERT_TIMESTAMP_TOLERANCE_SECONDS = 300;
23
+
24
+ /**
25
+ * Rebuild the `<timestamp>.<body>` message an alert webhook is signed over, or
26
+ * return null when the timestamp is absent, unparseable, or outside the replay
27
+ * window.
28
+ */
29
+ function alertSignedMessage(
30
+ timestamp: string | undefined,
31
+ body: Buffer,
32
+ tolerance: number = ALERT_TIMESTAMP_TOLERANCE_SECONDS,
33
+ ): Buffer | null {
34
+ if (!timestamp || !/^\d+$/.test(timestamp)) {
35
+ return null;
36
+ }
37
+
38
+ if (Math.abs(Date.now() / 1000 - Number(timestamp)) > tolerance) {
39
+ return null;
40
+ }
41
+
42
+ return Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), body]);
43
+ }
44
+
45
+ const RESOURCE_TYPES: string[] = Object.values(ResourceType);
46
+
47
+ /**
48
+ * The signature covers the decompressed bytes, so decompression runs before the
49
+ * request is authenticated and needs its own ceiling.
50
+ */
51
+ const MAX_BODY_BYTES = 256 * 1024 * 1024;
52
+
10
53
  /**
11
54
  * Verify that a webhook request was sent by Scrapfly by comparing the
12
55
  * HMAC-SHA256 signature on the request body against the configured
13
56
  * signing secret.
14
57
  *
15
- * @param body Raw request body as received (verify BEFORE any decompression
16
- * or JSON parsing — the signature is computed on the bytes
17
- * Scrapfly sent on the wire).
58
+ * @param body Body as Scrapfly signed it: decompressed, but not JSON-parsed.
59
+ * Signing happens before `Content-Encoding` is applied, so a
60
+ * compressed request must be inflated first.
18
61
  * @param signature Value of the `X-Scrapfly-Webhook-Signature` header
19
- * (uppercase hex digest).
20
- * @param signingSecret Webhook signing secret from the dashboard, passed as-is
21
- * (UTF-8 string; not hex-encoded).
62
+ * (uppercase hex digest). The `-Lowercase` header carries
63
+ * the same digest and is accepted too.
64
+ * @param signingSecret Webhook signing secret, passed as-is (UTF-8 string; not
65
+ * hex-encoded). Pass an array to accept any of several
66
+ * secrets, for key rotation.
22
67
  * @returns `true` if the signature matches.
23
68
  */
24
- export function verifySignature(body: Buffer, signature: string, signingSecret: string): boolean {
25
- const hmac = crypto.createHmac('sha256', Buffer.from(signingSecret, 'utf8'));
26
- hmac.update(body);
27
- const computed = hmac.digest('hex').toUpperCase();
28
- const received = signature.toUpperCase();
29
- if (computed.length !== received.length) {
69
+ export function verifySignature(
70
+ body: Buffer,
71
+ signature: string | undefined | null,
72
+ signingSecret: string | string[],
73
+ ): boolean {
74
+ const secrets = (Array.isArray(signingSecret) ? signingSecret : [signingSecret]).filter(Boolean);
75
+
76
+ // An empty key is a usable HMAC key: verifying against one accepts a digest
77
+ // anybody can compute.
78
+ if (secrets.length === 0) {
79
+ throw new Error('verifySignature requires a non-empty signing secret');
80
+ }
81
+
82
+ if (!signature) {
30
83
  return false;
31
84
  }
32
- return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(received));
85
+
86
+ const received = Buffer.from(signature.trim().toUpperCase(), 'utf8');
87
+
88
+ return secrets.some((secret) => {
89
+ const hmac = crypto.createHmac('sha256', Buffer.from(secret, 'utf8'));
90
+ hmac.update(body);
91
+ const computed = Buffer.from(hmac.digest('hex').toUpperCase(), 'utf8');
92
+
93
+ // timingSafeEqual throws on a length mismatch; hex digests are fixed-width.
94
+ if (computed.length !== received.length) {
95
+ return false;
96
+ }
97
+
98
+ return crypto.timingSafeEqual(computed, received);
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Reverse the `Content-Encoding` applied to a webhook body.
104
+ */
105
+ function decompress(body: Buffer, contentEncoding: string | undefined, limit: number): Buffer {
106
+ // maxOutputLength aborts mid-inflate; without it the ceiling is buffer.kMaxLength.
107
+ const options = { maxOutputLength: limit };
108
+
109
+ switch ((contentEncoding || '').toLowerCase()) {
110
+ case '':
111
+ case 'none':
112
+ case 'identity':
113
+ return body;
114
+ case 'gzip':
115
+ case 'gz':
116
+ return zlib.gunzipSync(body, options);
117
+ case 'deflate':
118
+ return zlib.inflateSync(body, options);
119
+ case 'br':
120
+ case 'brotli':
121
+ return zlib.brotliDecompressSync(body, options);
122
+ case 'zstd': {
123
+ const zstdDecompressSync = (zlib as any).zstdDecompressSync;
124
+ if (typeof zstdDecompressSync !== 'function') {
125
+ throw new Error('zstd webhook bodies require Node 22+; set the webhook content encoding to gzip or none');
126
+ }
127
+ return zstdDecompressSync(body, options);
128
+ }
129
+ default:
130
+ throw new Error(`Unsupported webhook content encoding: ${contentEncoding}`);
131
+ }
33
132
  }
34
133
 
134
+ /** Raised when a body is larger than the configured cap, before or after inflation. */
135
+ class WebhookBodyTooLarge extends Error {}
35
136
 
36
137
  /**
37
- * Start a tiny Express server that receives Scrapfly webhook callbacks
38
- * and dispatches them to the provided `callback`. Intended for quick
39
- * integration and local development; production setups should wire
40
- * Scrapfly webhooks directly into their own HTTP stack via
138
+ * Collect the request body without a body parser in front of it. body-parser
139
+ * answers 415 for any encoding it cannot inflate itself, and hands back a
140
+ * parsed object where the signature needs bytes.
141
+ */
142
+ function readBody(req: any, limit: number): Promise<Buffer> {
143
+ // express.raw() leaves the bytes on req.body.
144
+ if (Buffer.isBuffer(req.body)) {
145
+ return Promise.resolve(req.body);
146
+ }
147
+
148
+ // An object-producing parser (express.json()) already drained the stream, so
149
+ // 'data' and 'end' never fire again and awaiting them parks the request until the
150
+ // socket times out. Its output is unusable here: the signature covers bytes.
151
+ if (req.readableEnded || req.complete) {
152
+ return Promise.reject(
153
+ new Error(
154
+ 'the request body was already consumed by another body parser. Mount the Scrapfly ' +
155
+ 'webhook route on an app without a global express.json()/urlencoded(), or register ' +
156
+ 'those parsers after createServer(), so the raw bytes reach signature verification.',
157
+ ),
158
+ );
159
+ }
160
+
161
+ return new Promise((resolve, reject) => {
162
+ const chunks: Buffer[] = [];
163
+ let size = 0;
164
+
165
+ req.on('data', (chunk: Buffer) => {
166
+ size += chunk.length;
167
+
168
+ if (size > limit) {
169
+ reject(new WebhookBodyTooLarge(`webhook body exceeds ${limit} bytes`));
170
+ return;
171
+ }
172
+
173
+ chunks.push(chunk);
174
+ });
175
+ req.on('end', () => resolve(Buffer.concat(chunks)));
176
+ req.on('error', reject);
177
+ });
178
+ }
179
+
180
+ /**
181
+ * Start a tiny Express server that receives Scrapfly webhook callbacks,
182
+ * verifies their signature, and dispatches them to the provided `callback`.
183
+ * Intended for quick integration and local development; production setups
184
+ * should wire Scrapfly webhooks directly into their own HTTP stack via
41
185
  * {@link verifySignature}.
42
186
  *
187
+ * Every request must be signed. A body with no `X-Scrapfly-Webhook-Signature`
188
+ * is rejected with 401 rather than delivered.
189
+ *
43
190
  * Requires the `express` package to be installed.
44
191
  *
45
- * @param callback Invoked with the parsed webhook body, its resource
46
- * type (`scrape` or `ping`), and the raw Express request.
192
+ * @param signingSecrets Webhook signing secret(s) from your webhook settings.
193
+ * @param callback Invoked with the verified body, its resource type, and the
194
+ * raw Express request. Awaited, so an async callback's failure yields 500. Bodies are JSON-parsed when the content type says so;
195
+ * binary payloads (screenshot images) arrive as a Buffer.
47
196
  * @param app Optional pre-configured Express app to mount on.
197
+ * @param maxBodyBytes Reject bodies larger than this, before any decompression.
48
198
  * @returns The underlying Express app (for further configuration or `.listen()`).
49
199
  */
50
200
  export async function createServer(
51
- callback: (data: any, resourceType: string, request: any) => void,
201
+ signingSecrets: string | string[],
202
+ callback: (data: any, resourceType: string, request: any) => void | Promise<void>,
52
203
  app?: any,
204
+ maxBodyBytes: number = MAX_BODY_BYTES,
53
205
  ): Promise<any> {
206
+ if (!signingSecrets || (Array.isArray(signingSecrets) && signingSecrets.length === 0)) {
207
+ throw new Error('createServer requires the webhook signing secret(s) from your Scrapfly dashboard');
208
+ }
209
+
54
210
  let express: any;
55
211
  try {
56
212
  const expressModule = await import('express');
@@ -63,33 +219,73 @@ export async function createServer(
63
219
  app = express();
64
220
  }
65
221
 
66
- const jsonMiddleware = express.json({
67
- verify: (req: any, _res: any, buf: Buffer) => {
68
- req.rawBody = buf;
69
- },
70
- });
222
+ app.post('/webhook', async (req: any, res: any) => {
223
+ const resourceType = req.headers['x-scrapfly-webhook-resource-type'];
224
+ // The digest is sent under both spellings; accept either.
225
+ const signature = req.headers['x-scrapfly-webhook-signature'] ||
226
+ req.headers['x-scrapfly-webhook-signature-lowercase'];
227
+
228
+ if (!RESOURCE_TYPES.includes(resourceType)) {
229
+ // Attacker-controlled and served as text/html: never echo it back.
230
+ log.error('Unsupported resource type:', JSON.stringify(resourceType));
231
+ return res.status(400).send('unsupported resource type');
232
+ }
233
+
234
+ // A ping sent while a webhook is being created carries no signature. Answer the
235
+ // reachability probe, but never hand an unverified body to the callback: the
236
+ // resource type is as unauthenticated as the signature.
237
+ if (resourceType === ResourceType.PING && !signature) {
238
+ return res.status(200).send('');
239
+ }
71
240
 
72
- app.post('/webhook', jsonMiddleware, (req: any, res: any) => {
241
+ let body: Buffer;
73
242
  try {
74
- const resourceType = req.headers['x-scrapfly-webhook-resource-type'];
243
+ body = decompress(await readBody(req, maxBodyBytes), req.headers['content-encoding'], maxBodyBytes);
244
+ } catch (e) {
245
+ log.error('Webhook decoding error:', e);
246
+ // Decoding runs before verification, so these failures are reachable unauthenticated.
247
+ return res.status(e instanceof WebhookBodyTooLarge ? 413 : 400).send('');
248
+ }
249
+
250
+ let signedMessage: Buffer | null = body;
75
251
 
76
- if (resourceType !== 'scrape' && resourceType !== 'ping') {
77
- log.error(`Unsupported resource type: ${resourceType}`);
78
- return res.status(400).send(`this webhook server only supports scrape and ping calls`);
252
+ if (resourceType === ResourceType.ALERT) {
253
+ signedMessage = alertSignedMessage(req.headers['x-scrapfly-webhook-timestamp'], body);
254
+
255
+ if (signedMessage === null) {
256
+ log.error(`Rejected alert webhook with a missing or stale timestamp from ${req.ip}`);
257
+ return res.status(401).send('');
79
258
  }
259
+ }
80
260
 
81
- const data: any = req.body;
261
+ if (!verifySignature(signedMessage, signature, signingSecrets)) {
262
+ log.error(`Rejected unsigned or mis-signed ${resourceType} webhook from ${req.ip}`);
263
+ return res.status(401).send('');
264
+ }
82
265
 
83
- try {
84
- callback(data, resourceType, req);
85
- res.status(200).send('');
86
- } catch (e) {
87
- log.error('Callback error:', e);
88
- res.status(500).send('');
266
+ let data: any = body;
267
+ const contentType = (req.headers['content-type'] || '') as string;
268
+ try {
269
+ if (contentType.startsWith('application/json')) {
270
+ data = JSON.parse(body.toString('utf8'));
271
+ } else if (contentType.startsWith('application/msgpack')) {
272
+ // application/msgpack is an offered webhook content type.
273
+ const { decode } = await import('@msgpack/msgpack');
274
+ data = decode(body);
89
275
  }
90
276
  } catch (e) {
91
- log.error('Webhook processing error:', e);
92
- res.status(400).send('');
277
+ log.error('Webhook body parse error:', e);
278
+ return res.status(400).send('');
279
+ }
280
+
281
+ try {
282
+ // Awaited: an un-awaited async callback rejects into an unhandled rejection,
283
+ // which terminates the process on Node >= 15.
284
+ await callback(data, resourceType, req);
285
+ return res.status(200).send('');
286
+ } catch (e) {
287
+ log.error('Callback error:', e);
288
+ return res.status(500).send('');
93
289
  }
94
290
  });
95
291