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
@@ -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