Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
feat: implement global storage access checking and use it to prevent unwanted side effects in adaptive crawler (#2371)
Jan Bucharfb3b7da40252
diff --git a/packages/core/src/storages/access_checking.ts b/packages/core/src/storages/access_checking.tsnew file mode 100644index 000000000..cb123d60e--- /dev/null+++ b/packages/core/src/storages/access_checking.ts@@ -0,0 +1,18 @@+import { AsyncLocalStorage } from 'async_hooks';++import type { Awaitable } from '../typedefs';++const storage = new AsyncLocalStorage<{ checkFunction:() => void }>();++/**+ * Invoke a storage access checker function defined using {@link withCheckedStorageAccess} higher up in the call stack.+ */+export const checkStorageAccess = () => storage.getStore()?.checkFunction();++/**+ * Define a storage access checker function that should be used by calls to {@link checkStorageAccess} in the callbacks.+ *+ * @param checkFunction The check function that should be invoked by {@link checkStorageAccess} calls+ * @param callback The code that should be invoked with the `checkFunction` setting+ */+export const withCheckedStorageAccess = async <T>(checkFunction: () => void, callback: () => Awaitable<T>) => storage.run({ checkFunction }, callback);diff --git a/packages/core/src/storages/dataset.ts b/packages/core/src/storages/dataset.tsindex 8690d928c..689a55cf0 100644--- a/packages/core/src/storages/dataset.ts+++ b/packages/core/src/storages/dataset.ts@@ -3,6 +3,7 @@ import type { DatasetClient, DatasetInfo, Dictionary, StorageClient } from '@craimport { stringify } from 'csv-stringify/sync';import ow from 'ow';+import { checkStorageAccess } from './access_checking';import { KeyValueStore } from './key_value_store';import type { StorageManagerOptions } from './storage_manager';import { StorageManager } from './storage_manager';@@ -260,6 +261,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.*/async pushData(data: Data | Data[]): Promise<void> {+ checkStorageAccess();+ow(data, 'data', ow.object);const dispatch = async (payload: string) => this.client.pushItems(payload);const limit = MAX_PAYLOAD_SIZE_BYTES - Math.ceil(MAX_PAYLOAD_SIZE_BYTES * SAFETY_BUFFER_PERCENT);@@ -284,6 +287,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* Returns {@apilink DatasetContent} object holding the items in the dataset based on the provided parameters.*/async getData(options: DatasetDataOptions = {}): Promise<DatasetContent<Data>> {+ checkStorageAccess();+try {return await this.client.listItems(options);} catch (e) {@@ -300,6 +305,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* via the `listItems()` client method, which gives you only paginated results.*/async export(options: DatasetExportOptions = {}): Promise<Data[]> {+ checkStorageAccess();+const items: Data[] = [];const fetchNextChunk = async (offset = 0): Promise<void> => {@@ -379,6 +386,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* @param [options] An optional options object where you can provide the dataset and target KVS name.*/static async exportToJSON(key: string, options?: DatasetExportToOptions) {+ checkStorageAccess();+const dataset = await this.open(options?.fromDataset);await dataset.exportToJSON(key, options);}@@ -390,6 +399,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* @param [options] An optional options object where you can provide the dataset and target KVS name.*/static async exportToCSV(key: string, options?: DatasetExportToOptions) {+ checkStorageAccess();+const dataset = await this.open(options?.fromDataset);await dataset.exportToCSV(key, options);}@@ -417,6 +428,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* ```*/async getInfo(): Promise<DatasetInfo | undefined> {+ checkStorageAccess();+return this.client.get();}@@ -441,6 +454,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* @default 0*/async forEach(iteratee: DatasetConsumer<Data>, options: DatasetIteratorOptions = {}, index = 0): Promise<void> {+ checkStorageAccess();+if (!options.offset) options.offset = 0;if (options.format && options.format !== 'json') throw new Error('Dataset.forEach/map/reduce() support only a "json" format.');if (!options.limit) options.limit = DATASET_ITERATORS_DEFAULT_LIMIT;@@ -468,6 +483,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* @param [options] All `map()` parameters.*/async map<R>(iteratee: DatasetMapper<Data, R>, options: DatasetIteratorOptions = {}): Promise<R[]> {+ checkStorageAccess();+const result: R[] = [];await this.forEach(async (item, index) => {@@ -494,6 +511,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* @param [options] All `reduce()` parameters.*/async reduce<T>(iteratee: DatasetReducer<T, Data>, memo: T, options: DatasetIteratorOptions = {}): Promise<T> {+ checkStorageAccess();+let currentMemo: T = memo;const wrappedFunc: DatasetConsumer<Data> = async (item, index) => {@@ -518,6 +537,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* depending on the mode of operation.*/async drop(): Promise<void> {+ checkStorageAccess();+await this.client.delete();const manager = StorageManager.getManager(Dataset, this.config);manager.closeStorage(this);@@ -538,6 +559,8 @@ export class Dataset<Data extends Dictionary = Dictionary> {* @param [options] Storage manager options.*/static async open<Data extends Dictionary = Dictionary>(datasetIdOrName?: string | null, options: StorageManagerOptions = {}): Promise<Dataset<Data>> {+ checkStorageAccess();+ow(datasetIdOrName, ow.optional.string);ow(options, ow.object.exactShape({config: ow.optional.object.instanceOf(Configuration),diff --git a/packages/core/src/storages/index.ts b/packages/core/src/storages/index.tsindex c51ef0b1e..76490dbde 100644--- a/packages/core/src/storages/index.ts+++ b/packages/core/src/storages/index.ts@@ -6,3 +6,4 @@ export * from './request_queue';export * from './request_queue_v2';export * from './storage_manager';export * from './utils';+export * from './access_checking';diff --git a/packages/core/src/storages/key_value_store.ts b/packages/core/src/storages/key_value_store.tsindex ad6951c40..5c3077cff 100644--- a/packages/core/src/storages/key_value_store.ts+++ b/packages/core/src/storages/key_value_store.ts@@ -7,6 +7,7 @@ import type { Dictionary, KeyValueStoreClient, StorageClient } from '@crawlee/tyimport JSON5 from 'json5';import ow, { ArgumentError } from 'ow';+import { checkStorageAccess } from './access_checking';import type { StorageManagerOptions } from './storage_manager';import { StorageManager } from './storage_manager';import { purgeDefaultStorages } from './utils';@@ -215,6 +216,8 @@ export class KeyValueStore {* on the MIME content type of the record, or `null` if the key is missing from the store.*/async getValue<T = unknown>(key: string, defaultValue?: T): Promise<T | null> {+ checkStorageAccess();+ow(key, ow.string.nonEmpty);const record = await this.client.getRecord(key);@@ -228,11 +231,15 @@ export class KeyValueStore {* @returns `true` if the record exists, `false` if it does not.*/async recordExists(key: string): Promise<boolean> {+ checkStorageAccess();+ow(key, ow.string.nonEmpty);return this.client.recordExists(key);}async getAutoSavedValue<T extends Dictionary = Dictionary>(key: string, defaultValue = {} as T): Promise<T> {+ checkStorageAccess();+if (this.cache.has(key)) {return this.cache.get(key) as T;}@@ -311,6 +318,8 @@ export class KeyValueStore {* @param [options] Record options.*/async setValue<T>(key: string, value: T | null, options: RecordOptions = {}): Promise<void> {+ checkStorageAccess();+ow(key, 'key', ow.string.nonEmpty);ow(key, ow.string.validate((k) => ({validator: ow.isValid(k, ow.string.matches(KEY_VALUE_STORE_KEY_REGEX)),@@ -361,6 +370,8 @@ export class KeyValueStore {* depending on the mode of operation.*/async drop(): Promise<void> {+ checkStorageAccess();+await this.client.delete();const manager = StorageManager.getManager(KeyValueStore, this.config);manager.closeStorage(this);@@ -368,6 +379,8 @@ export class KeyValueStore {/** @internal */clearCache(): void {+ checkStorageAccess();+this.cache.clear();}@@ -393,6 +406,8 @@ export class KeyValueStore {* @param [options] All `forEachKey()` parameters.*/async forEachKey(iteratee: KeyConsumer, options: KeyValueStoreIteratorOptions = {}): Promise<void> {+ checkStorageAccess();+return this._forEachKey(iteratee, options);}@@ -428,6 +443,8 @@ export class KeyValueStore {* @param [options] Storage manager options.*/static async open(storeIdOrName?: string | null, options: StorageManagerOptions = {}): Promise<KeyValueStore> {+ checkStorageAccess();+ow(storeIdOrName, ow.optional.any(ow.string, ow.null));ow(options, ow.object.exactShape({config: ow.optional.object.instanceOf(Configuration),diff --git a/packages/core/src/storages/request_provider.ts b/packages/core/src/storages/request_provider.tsindex 64995532c..59efeb8a1 100644--- a/packages/core/src/storages/request_provider.ts+++ b/packages/core/src/storages/request_provider.ts@@ -13,6 +13,7 @@ import type {import { chunk, downloadListOfUrls, sleep } from '@crawlee/utils';import ow from 'ow';+import { checkStorageAccess } from './access_checking';import type { IStorage, StorageManagerOptions } from './storage_manager';import { StorageManager } from './storage_manager';import { QUERY_HEAD_MIN_LENGTH, STORAGE_CONSISTENCY_DELAY_MILLIS, getRequestId, purgeDefaultStorages } from './utils';@@ -103,6 +104,8 @@ export abstract class RequestProvider implements IStorage {* @param [options] Request queue operation options.*/async addRequest(requestLike: Source, options: RequestQueueOperationOptions = {}): Promise<RequestQueueOperationInfo> {+ checkStorageAccess();+ow(requestLike, ow.object);ow(options, ow.object.exactShape({forefront: ow.optional.boolean,@@ -172,6 +175,8 @@ export abstract class RequestProvider implements IStorage {requestsLike: Source[],options: RequestQueueOperationOptions = {},): Promise<BatchAddRequestsResult> {+ checkStorageAccess();+ow(requestsLike, ow.array);ow(options, ow.object.exactShape({forefront: ow.optional.boolean,@@ -271,6 +276,8 @@ export abstract class RequestProvider implements IStorage {* @param options Options for the request queue*/async addRequestsBatched(requests: (string | Source)[], options: AddRequestsBatchedOptions = {}): Promise<AddRequestsBatchedResult> {+ checkStorageAccess();+ow(requests, ow.array.ofType(ow.any(ow.string,ow.object.partialShape({ url: ow.string, id: ow.undefined }),@@ -358,6 +365,8 @@ export abstract class RequestProvider implements IStorage {* @returns Returns the request object, or `null` if it was not found.*/async getRequest<T extends Dictionary = Dictionary>(id: string): Promise<Request<T> | null> {+ checkStorageAccess();+ow(id, ow.string);const requestOptions = await this.client.getRequest(id);@@ -375,6 +384,8 @@ export abstract class RequestProvider implements IStorage {* Handled requests will never again be returned by the `fetchNextRequest` function.*/async markRequestHandled(request: Request): Promise<RequestQueueOperationInfo | null> {+ checkStorageAccess();+ow(request, ow.object.partialShape({id: ow.string,uniqueKey: ow.string,@@ -410,6 +421,8 @@ export abstract class RequestProvider implements IStorage {* For example, this lets you store the number of retries or error messages for the request.*/async reclaimRequest(request: Request, options: RequestQueueOperationOptions = {}): Promise<RequestQueueOperationInfo | null> {+ checkStorageAccess();+ow(request, ow.object.partialShape({id: ow.string,uniqueKey: ow.string,@@ -512,6 +525,8 @@ export abstract class RequestProvider implements IStorage {* depending on the mode of operation.*/async drop(): Promise<void> {+ checkStorageAccess();+await this.client.delete();const manager = StorageManager.getManager(this.constructor as Constructor<IStorage>, this.config);manager.closeStorage(this);@@ -557,6 +572,8 @@ export abstract class RequestProvider implements IStorage {* ```*/async getInfo(): Promise<RequestQueueInfo | undefined> {+ checkStorageAccess();+return this.client.get();}@@ -626,6 +643,8 @@ export abstract class RequestProvider implements IStorage {* @param [options] Open Request Queue options.*/static async open(queueIdOrName?: string | null, options: StorageManagerOptions = {}): Promise<RequestProvider> {+ checkStorageAccess();+ow(queueIdOrName, ow.optional.any(ow.string, ow.null));ow(options, ow.object.exactShape({config: ow.optional.object.instanceOf(Configuration),diff --git a/packages/core/src/storages/request_queue.ts b/packages/core/src/storages/request_queue.tsindex 9ca1c22fd..d4e6aa35b 100644--- a/packages/core/src/storages/request_queue.ts+++ b/packages/core/src/storages/request_queue.ts@@ -4,6 +4,7 @@ import { REQUEST_QUEUE_HEAD_MAX_LIMIT } from '@apify/consts';import type { Dictionary,} from '@crawlee/types';+import { checkStorageAccess } from './access_checking';import type { RequestProviderOptions } from './request_provider';import { RequestProvider } from './request_provider';import {@@ -113,6 +114,8 @@ export class RequestQueue extends RequestProvider {* Returns the request object or `null` if there are no more pending requests.*/override async fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null> {+ checkStorageAccess();+await this.ensureHeadIsNonEmpty();const nextRequestId = this.queueHeadIds.removeFirst();@@ -282,6 +285,8 @@ export class RequestQueue extends RequestProvider {// RequestQueue v1 behavior overrides belowoverride async isFinished(): Promise<boolean> {+ checkStorageAccess();+if ((Date.now() - +this.lastActivity) > this.internalTimeoutMillis) {const message = `The request queue seems to be stuck for ${this.internalTimeoutMillis / 1e3}s, resetting internal state.`;this.log.warning(message, { inProgress: [...this.inProgress] });@@ -295,26 +300,36 @@ export class RequestQueue extends RequestProvider {}override async addRequest(...args: Parameters<RequestProvider['addRequest']>) {+ checkStorageAccess();+this.lastActivity = new Date();return super.addRequest(...args);}override async addRequests(...args: Parameters<RequestProvider['addRequests']>) {+ checkStorageAccess();+this.lastActivity = new Date();return super.addRequests(...args);}override async addRequestsBatched(...args: Parameters<RequestProvider['addRequestsBatched']>) {+ checkStorageAccess();+this.lastActivity = new Date();return super.addRequestsBatched(...args);}override async markRequestHandled(...args: Parameters<RequestProvider['markRequestHandled']>) {+ checkStorageAccess();+this.lastActivity = new Date();return super.markRequestHandled(...args);}override async reclaimRequest(...args: Parameters<RequestProvider['reclaimRequest']>) {+ checkStorageAccess();+this.lastActivity = new Date();return super.reclaimRequest(...args);}diff --git a/packages/core/src/storages/request_queue_v2.ts b/packages/core/src/storages/request_queue_v2.tsindex 28e59955b..0808bd4a9 100644--- a/packages/core/src/storages/request_queue_v2.ts+++ b/packages/core/src/storages/request_queue_v2.ts@@ -1,5 +1,6 @@import type { Dictionary } from '@crawlee/types';+import { checkStorageAccess } from './access_checking';import type { RequestQueueOperationInfo, RequestProviderOptions } from './request_provider';import { RequestProvider } from './request_provider';import {@@ -46,6 +47,8 @@ class RequestQueue extends RequestProvider {* Caches information about request to beware of unneeded addRequest() calls.*/protected override _cacheRequest(cacheKey: string, queueOperationInfo: RequestQueueOperationInfo): void {+ checkStorageAccess();+super._cacheRequest(cacheKey, queueOperationInfo);this.requestCache.add(queueOperationInfo.requestId, {@@ -75,6 +78,8 @@ class RequestQueue extends RequestProvider {* Returns the request object or `null` if there are no more pending requests.*/override async fetchNextRequest<T extends Dictionary = Dictionary>(): Promise<Request<T> | null> {+ checkStorageAccess();+await this.ensureHeadIsNonEmpty();const nextRequestId = this.queueHeadIds.removeFirst();@@ -137,6 +142,8 @@ class RequestQueue extends RequestProvider {}override async reclaimRequest(...args: Parameters<RequestProvider['reclaimRequest']>): ReturnType<RequestProvider['reclaimRequest']> {+ checkStorageAccess();+const res = await super.reclaimRequest(...args);if (res) {@@ -154,6 +161,8 @@ class RequestQueue extends RequestProvider {}protected async ensureHeadIsNonEmpty() {+ checkStorageAccess();+// Stop fetching if we are paused for migrationif (this.queuePausedForMigration) {return;@@ -172,6 +181,8 @@ class RequestQueue extends RequestProvider {}private async _listHeadAndLock(): Promise<void> {+ checkStorageAccess();+const headData = await this.client.listAndLockHead({ limit: 25, lockSecs: this.requestLockSecs });for (const { id, uniqueKey } of headData.items) {@@ -191,6 +202,8 @@ class RequestQueue extends RequestProvider {}private async getOrHydrateRequest<T extends Dictionary = Dictionary>(requestId: string): Promise<Request<T> | null> {+ checkStorageAccess();+const cachedEntry = this.requestCache.get(requestId);if (!cachedEntry) {@@ -273,6 +286,8 @@ class RequestQueue extends RequestProvider {}private async _prolongRequestLock(requestId: string): Promise<Date | null> {+ checkStorageAccess();+try {const res = await this.client.prolongRequestLock(requestId, { lockSecs: this.requestLockSecs });return res.lockExpiresAt;@@ -287,6 +302,8 @@ class RequestQueue extends RequestProvider {}protected override _reset() {+ checkStorageAccess();+super._reset();this._listHeadAndLockPromise = null;}@@ -296,6 +313,8 @@ class RequestQueue extends RequestProvider {}protected async _clearPossibleLocks() {+ checkStorageAccess();+this.queuePausedForMigration = true;let requestId: string | null;diff --git a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.tsindex 02270b99b..1fcc41617 100644--- a/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts+++ b/packages/playwright-crawler/src/internals/adaptive-playwright-crawler.ts@@ -1,7 +1,7 @@import { addTimeoutToPromise } from '@apify/timeout';import { extractUrlsFromPage } from '@crawlee/browser';import type { RestrictedCrawlingContext, StatisticState, StatisticPersistedState } from '@crawlee/core';-import { Configuration, RequestHandlerResult, Statistics } from '@crawlee/core';+import { Configuration, RequestHandlerResult, Statistics, withCheckedStorageAccess } from '@crawlee/core';import type { Awaitable, Dictionary } from '@crawlee/types';import { extractUrlsFromCheerio } from '@crawlee/utils';import { load, type Cheerio, type Element } from 'cheerio';@@ -261,6 +261,13 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {]);}+ protected allowStorageAccess<R, TArgs extends any[]>(func: (...args: TArgs) => Promise<R>): ((...args: TArgs) => Promise<R>) {+ return async (...args: TArgs) => withCheckedStorageAccess(+ () => { },+ async () => func(...args),+ );+ }+protected async runRequestHandlerInBrowser(crawlingContext: PlaywrightCrawlingContext<Dictionary>): Promise<Result<RequestHandlerResult>> {const result = new RequestHandlerResult(this.config, AdaptivePlaywrightCrawler.CRAWLEE_STATE_KEY);@@ -269,31 +276,36 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {new Proxy(this, {get: (target, propertyName, receiver) => {if (propertyName === 'userProvidedRequestHandler') {- return (playwrightContext: PlaywrightCrawlingContext) => this.adaptiveRequestHandler({- request: crawlingContext.request,- log: crawlingContext.log,- querySelector: async (selector, timeoutMs) => {- const locator = playwrightContext.page.locator(selector).first();- await locator.waitFor({ timeout: timeoutMs });- return (await playwrightContext.parseWithCheerio())(selector) as Cheerio<Element>;- },- enqueueLinks: async (options = {}) => {- const selector = options.selector ?? 'a';- const locator = playwrightContext.page.locator(selector).first();- await locator.waitFor();-- const urls = await extractUrlsFromPage(- playwrightContext.page,- selector,- options.baseUrl ?? playwrightContext.request.loadedUrl ?? playwrightContext.request.url,- );- await result.enqueueLinks({ ...options, urls });+ return (async (playwrightContext: PlaywrightCrawlingContext) => withCheckedStorageAccess(+ () => {+ throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');},- addRequests: result.addRequests,- pushData: result.pushData,- useState: result.useState,- getKeyValueStore: result.getKeyValueStore,- });+ () => this.adaptiveRequestHandler({+ request: crawlingContext.request,+ log: crawlingContext.log,+ querySelector: async (selector, timeoutMs) => {+ const locator = playwrightContext.page.locator(selector).first();+ await locator.waitFor({ timeout: timeoutMs });+ return (await playwrightContext.parseWithCheerio())(selector) as Cheerio<Element>;+ },+ enqueueLinks: async (options = {}) => {+ const selector = options.selector ?? 'a';+ const locator = playwrightContext.page.locator(selector).first();+ await locator.waitFor();++ const urls = await extractUrlsFromPage(+ playwrightContext.page,+ selector,+ options.baseUrl ?? playwrightContext.request.loadedUrl ?? playwrightContext.request.url,+ );+ await result.enqueueLinks({ ...options, urls });+ },+ addRequests: result.addRequests,+ pushData: result.pushData,+ useState: this.allowStorageAccess(result.useState),+ getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),+ }),+ ));}return Reflect.get(target, propertyName, receiver);},@@ -315,22 +327,27 @@ export class AdaptivePlaywrightCrawler extends PlaywrightCrawler {const $ = load(response.body);try {- await addTimeoutToPromise(- async () => this.adaptiveRequestHandler({- request: crawlingContext.request,- log: crawlingContext.log,- querySelector: (selector) => $(selector) as Cheerio<Element>,- enqueueLinks: async (options: Parameters<RestrictedCrawlingContext['enqueueLinks']>[0] = {}) => {- const urls = extractUrlsFromCheerio($, options.selector, options.baseUrl ?? loadedUrl);- await result.enqueueLinks({ ...options, urls });- },- addRequests: result.addRequests,- pushData: result.pushData,- useState: result.useState,- getKeyValueStore: result.getKeyValueStore,- }),- this.requestHandlerTimeoutInnerMillis,- 'Request handler timed out',+ await withCheckedStorageAccess(+ () => {+ throw new Error('Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler');+ },+ async () => addTimeoutToPromise(+ async () => this.adaptiveRequestHandler({+ request: crawlingContext.request,+ log: crawlingContext.log,+ querySelector: (selector) => $(selector) as Cheerio<Element>,+ enqueueLinks: async (options: Parameters<RestrictedCrawlingContext['enqueueLinks']>[0] = {}) => {+ const urls = extractUrlsFromCheerio($, options.selector, options.baseUrl ?? loadedUrl);+ await result.enqueueLinks({ ...options, urls });+ },+ addRequests: result.addRequests,+ pushData: result.pushData,+ useState: this.allowStorageAccess(result.useState),+ getKeyValueStore: this.allowStorageAccess(result.getKeyValueStore),+ }),+ this.requestHandlerTimeoutInnerMillis,+ 'Request handler timed out',+ ),);return { result, ok: true };diff --git a/test/core/crawlers/adaptive_playwright_crawler.test.ts b/test/core/crawlers/adaptive_playwright_crawler.test.tsindex 73dbd3892..489ad2b33 100644--- a/test/core/crawlers/adaptive_playwright_crawler.test.ts+++ b/test/core/crawlers/adaptive_playwright_crawler.test.ts@@ -1,6 +1,7 @@import type { Server } from 'http';import type { AddressInfo } from 'net';+import { KeyValueStore } from '@crawlee/core';import type { AdaptivePlaywrightCrawlerOptions } from '@crawlee/playwright';import {AdaptivePlaywrightCrawler, RequestList,@@ -261,4 +262,37 @@ describe('AdaptivePlaywrightCrawler', () => {expect((await store.getRecord('2')).value).toEqual({ content: 42 });expect((await store.getRecord('3')).value).toEqual({ content: 42 });});++ test('should not allow direct key-value store manipulation', async () => {+ const renderingTypePredictor = makeRiggedRenderingTypePredictor({ detectionProbabilityRecommendation: 0, renderingType: 'static' });++ const requestHandler: AdaptivePlaywrightCrawlerOptions['requestHandler'] = vi.fn(async () => {+ const store = await KeyValueStore.open();+ await store.setValue('1', { content: 42 });+ });++ const failedRequestHandler = vi.fn();++ const crawler = await makeOneshotCrawler(+ {+ requestHandler,+ renderingTypePredictor,+ maxRequestsPerCrawl: 3,+ maxRequestRetries: 0,+ failedRequestHandler,+ },+ [+ `http://${HOSTNAME}:${port}/static`,+ ],+ );++ await crawler.run();+ expect(failedRequestHandler.mock.calls).toHaveLength(1);+ expect((failedRequestHandler.mock.calls[0][1] as Error).message).toEqual(+ 'Directly accessing storage in a request handler is not allowed in AdaptivePlaywrightCrawler',+ );++ const store = localStorageEmulator.getKeyValueStore();+ expect(await store.getRecord('1')).toBeUndefined();+ });});