Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate to Prosopo Procaptcha #1

Closed
wants to merge 2 commits into from
Closed

Migrate to Prosopo Procaptcha #1

wants to merge 2 commits into from

Conversation

Bullrich
Copy link

@Bullrich Bullrich commented Feb 23, 2024

Fixes paritytech#337

PR to migrate rococo faucet from reCAPTCHA to Prosopo Procaptcha, which runs on the rococo test network.

More detail to follow...

Copy from paritytech#372

Summary by CodeRabbit

  • New Features

    • Added support for a new captcha provider, alongside reCAPTCHA.
    • Introduced Playwright test configurations for captcha interaction.
    • Updated the app to handle different captcha providers dynamically.
  • Bug Fixes

    • Renamed environment variables and parameters for consistency across the project.
    • Updated logic in components and utility functions to align with the new captcha provider integration.
  • Documentation

    • Updated README files with new configuration settings and explanations.
    • Revised field names and explanations in documentation to reflect changes in captcha handling.
  • Refactor

    • Modified existing classes and methods to support a broader range of captcha providers.
    • Enhanced testing configurations and environment setups for better captcha provider testing.
  • Chores

    • Updated dependencies and configurations in GitHub workflows.
    • Added new configuration settings in example environment files.

forgetso and others added 2 commits February 22, 2024 12:36
* working frontend temp

* temp

* package json fix

* npm version bump

* Drip request type changing to procaptcha

* Drip request type changing to procaptcha

* swapping all occurrences of recaptcha with procaptcha and adding captcha logic

* Renaming recaptcha files and updating imports

* adding Prosopo outputs to tests

* bugtesting

* Removing bundle and adding back regular tests

* changing frontend to use remote bundle

* Add CAPTCHA_PROVIDER config item

* add feature flag for captcha provider and update tests for procaptcha

* Add react deps

* Add test configs for both captcha providers

* lint:fix and yarn install

* add Paseo testnet config

* remove wococo testnet config

* Adding forgotten paseo deployment

* Address PR comments

* Fix dummy body

* Add debug

* Bump the npm_and_yarn group across 1 directories with 1 update (paritytech#368)

* Create e2e test environment for procaptcha

* remove rogue file

* Update zombienet config in workflow

* yarn.lock

* yarn.lock

* downgrade jest

* try fix for buildcheck

* Pin polkadot versions

* yarn.lock with 1.22.21

* try new yarn.lock

* Update faucet lockfile

* Procaptcha dev (#2)

* dev setup wip

* update docker setup for procaptcha

* Remove extra unecessary stuff

* Undo formatting

* Update mock provider URL to use prosopo subdomain

* bump prosopo versions

* add missing dep

* Update to working package versions

* Upgrade prosopo deps

* Add missing body parameter

---------

Co-authored-by: Hugh <[email protected]>
Co-authored-by: hugh <[email protected]>
Co-authored-by: Pierre Besson <[email protected]>
Co-authored-by: Yuri Volkov <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Copy link

coderabbitai bot commented Feb 23, 2024

Walkthrough

This set of changes introduces support for a decentralized captcha system by Prosopo, alongside maintaining support for Google's reCAPTCHA. It involves updating configurations, renaming variables to generalize captcha handling, adding support for Prosopo in both client and server components, and updating tests and documentation to reflect these changes. The transition aims to explore the feasibility of replacing Google's captcha with Prosopo's decentralized solution.

Changes

Files Change Summary
.env.example, client/.env, client/README.md, client/src/app.d.ts, client/src/lib/utils/captcha.ts, src/types.ts Introduced configurations and code changes to support both Prosopo and reCAPTCHA providers.
.github/workflows/E2E.yml, e2e/README.md, src/faucet.e2e.ts, src/test/setupE2E.ts, src/test/setupE2EProcaptcha.ts Updated E2E testing configurations and added setup for Prosopo captcha.
client/src/lib/components/CaptchaV2.svelte, client/src/lib/components/Form.svelte, client/src/lib/utils/faucetRequest.ts, client/tests/faucet.ts, src/server/routes/actions.spec.ts, src/server/routes/actions.ts Updated to handle captchaResponse and support dynamic captcha provider selection.
src/dripper/DripRequestHandler.spec.ts, src/dripper/DripRequestHandler.ts, src/dripper/Procaptcha.spec.ts, src/dripper/Procaptcha.ts, src/bot/index.ts, src/config.ts Added and updated server-side logic for captcha validation with Prosopo and reCAPTCHA.
.eslintignore, client/playwright.config.procaptcha.ts, client/playwright.config.recaptcha.ts, src/dripper/polkadot/PolkadotActions.ts, src/test/webhookHelpers.ts Miscellaneous updates including test configurations and minor code adjustments.

Assessment against linked issues

Objective Addressed Explanation
Migrate to Prosopo for captcha validation (paritytech#337) The changes introduce Prosopo as a captcha provider alongside reCAPTCHA, demonstrating a successful proof of concept for decentralized captcha validation on the Rococo parachain.

🐇✨
In fields of data, under skies of code,
A captcha change, on this day bestowed.
From centralized to chains that freely roam,
Prosopo's seeds in digital soil sown.
🌱🌟 A rabbit hops, with every test it passed,
Amongst the bytes, a decentralized contrast.
🚀🐰💻 To future bright, our journey now aligned,
With captchas fair, and privacy enshrined.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between a857c92 and 1c87e42.
Files ignored due to path filters (6)
  • client/package.json is excluded by: !**/*.json
  • client/tsconfig.json is excluded by: !**/*.json
  • client/yarn.lock is excluded by: !**/*.lock
  • e2e/zombienet.native.toml is excluded by: !**/*.toml
  • env.faucet.config.json is excluded by: !**/*.json
  • package.json is excluded by: !**/*.json
Files selected for processing (29)
  • .env.example (1 hunks)
  • .eslintignore (1 hunks)
  • .github/workflows/E2E.yml (1 hunks)
  • README.md (3 hunks)
  • client/.env (1 hunks)
  • client/README.md (1 hunks)
  • client/playwright.config.procaptcha.ts (1 hunks)
  • client/playwright.config.recaptcha.ts (1 hunks)
  • client/src/app.d.ts (2 hunks)
  • client/src/lib/components/CaptchaV2.svelte (4 hunks)
  • client/src/lib/components/Form.svelte (2 hunks)
  • client/src/lib/utils/captcha.ts (1 hunks)
  • client/src/lib/utils/faucetRequest.ts (1 hunks)
  • client/tests/faucet.ts (14 hunks)
  • e2e/README.md (3 hunks)
  • src/bot/index.ts (1 hunks)
  • src/config.ts (1 hunks)
  • src/dripper/DripRequestHandler.spec.ts (5 hunks)
  • src/dripper/DripRequestHandler.ts (3 hunks)
  • src/dripper/Procaptcha.spec.ts (1 hunks)
  • src/dripper/Procaptcha.ts (1 hunks)
  • src/dripper/polkadot/PolkadotActions.ts (3 hunks)
  • src/faucet.e2e.ts (8 hunks)
  • src/server/routes/actions.spec.ts (3 hunks)
  • src/server/routes/actions.ts (3 hunks)
  • src/test/setupE2E.ts (6 hunks)
  • src/test/setupE2EProcaptcha.ts (1 hunks)
  • src/test/webhookHelpers.ts (1 hunks)
  • src/types.ts (2 hunks)
Files skipped from review due to trivial changes (3)
  • .eslintignore
  • client/src/lib/utils/captcha.ts
  • src/config.ts
Additional comments: 51
client/playwright.config.recaptcha.ts (1)
  • 8-9: The introduction of PUBLIC_CAPTCHA_PROVIDER set to "recaptcha" and the renaming of PUBLIC_CAPTCHA_KEY to PUBLIC_RECAPTCHA_KEY seem to contradict the PR's objective of migrating from Google's reCAPTCHA to Prosopo Procaptcha. Please verify if these changes are intended or if there's a misunderstanding regarding the captcha provider to be used.
client/playwright.config.procaptcha.ts (1)
  • 8-11: The configuration changes to support Prosopo Procaptcha, including the introduction of PUBLIC_CAPTCHA_PROVIDER set to "procaptcha" and the addition of PUBLIC_PROSOPO_SITE_KEY, align well with the PR's objectives of migrating to a decentralized captcha solution. These changes are correctly implemented for the intended migration.
client/.env (1)
  • 2-3: The changes in the .env file, including the renaming of PUBLIC_CAPTCHA_KEY to PUBLIC_RECAPTCHA_KEY, the addition of PUBLIC_PROSOPO_SITE_KEY, and setting PUBLIC_CAPTCHA_PROVIDER to procaptcha, are consistent with the migration to Prosopo Procaptcha. Please confirm if the intention is to support both captcha systems simultaneously or to fully migrate to Prosopo, as both PUBLIC_RECAPTCHA_KEY and PUBLIC_PROSOPO_SITE_KEY are present.

Also applies to: 11-11

client/src/app.d.ts (1)
  • 12-13: The changes to the captcha interfaces, including renaming Captcha to Recaptcha and adding a new Procaptcha interface, are well-implemented to support both reCAPTCHA and Prosopo Procaptcha. This approach aligns with the flexibility to potentially support multiple captcha providers. Please ensure that the rest of the client-side code correctly utilizes these interfaces based on the configured captcha provider.

Also applies to: 19-44

client/src/lib/components/Form.svelte (2)
  • 2-2: The import statement has been updated to include PUBLIC_CAPTCHA_PROVIDER, PUBLIC_PROSOPO_SITE_KEY, and PUBLIC_RECAPTCHA_KEY. This change supports the integration of both Google reCAPTCHA and Prosopo Procaptcha by allowing the component to dynamically select the appropriate captcha key based on the environment configuration.
  • 62-69: The logic for dynamically selecting the captcha key and provider has been implemented correctly. It uses a ternary operator to choose between PUBLIC_PROSOPO_SITE_KEY and PUBLIC_RECAPTCHA_KEY based on the value of PUBLIC_CAPTCHA_PROVIDER. This approach ensures that the component can support both captcha systems seamlessly. Additionally, the on:token event handler is correctly set up to handle captcha token events.
README.md (3)
  • 54-54: The JSON payload for the curl command has been updated to use captchaResponse instead of recaptcha. This change aligns with the migration to a more flexible captcha handling system that can accommodate different providers, including Prosopo Procaptcha.
  • 79-79: The JSON payload in the React example has been updated to use captchaResponse instead of recaptcha. This change is consistent with the broader migration efforts and ensures that the documentation reflects the current implementation.
  • 92-111: The explanation text has been updated to include details about using a verified rococo address or a recaptcha token with a specific sitekey and secret for testing purposes. This addition provides valuable context for users and developers, helping them understand how to test the faucet functionality with both Prosopo Procaptcha and Google reCAPTCHA.
src/dripper/DripRequestHandler.ts (5)
  • 4-4: The import statements have been updated to include CaptchaProvider and Procaptcha, supporting the integration of the new captcha system. This change is essential for enabling the DripRequestHandler to work with different captcha providers.
  • 24-27: The introduction of the HandleRequestOpts type is a good practice as it unifies the options for handling requests, making the code more maintainable and easier to understand. This change supports the handling of both internal and external requests with different requirements.
  • 31-31: Replacing the recaptcha property with captchaService in the DripRequestHandler constructor is a positive change. It generalizes the captcha handling mechanism, allowing for the integration of different captcha services, such as Prosopo Procaptcha and Google reCAPTCHA.
  • 34-43: The updated handleRequest method now correctly handles different types of requests based on the external flag and uses the appropriate captcha service for validation. This approach enhances the flexibility and scalability of the captcha validation process.
  • 73-76: The modification of the getDripRequestHandlerInstance function to accept a captchaProvider parameter and instantiate the appropriate captcha service based on the provider is a significant improvement. It ensures that the system can easily switch between different captcha providers, aligning with the project's goal of exploring decentralized captcha solutions.
client/src/lib/components/CaptchaV2.svelte (5)
  • 1-1: The script tag has been correctly updated to include type="module", which is necessary for importing ES modules in Svelte components. This change supports the integration of the new captcha system.
  • 4-4: The import statement for CaptchaProvider has been added, enabling the component to use the constants defined for different captcha providers. This is a crucial step for supporting multiple captcha systems.
  • 7-7: The introduction of the captchaProvider prop allows the component to dynamically select the captcha system based on the environment configuration. This flexibility is essential for supporting both Google reCAPTCHA and Prosopo Procaptcha.
  • 23-64: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [17-61]

The updated logic in the window.captchaLoaded function correctly handles the rendering of captcha based on the selected captchaProvider. This approach ensures that the component can seamlessly switch between different captcha systems. Additionally, the logic to force a new captcha on page reload for procaptcha is a thoughtful addition that enhances the user experience.

  • 77-86: The conditional rendering of the captcha script source based on the captchaProvider selected is implemented correctly. This ensures that the correct script is loaded for the selected captcha system, whether it's Google reCAPTCHA or Prosopo Procaptcha.
e2e/README.md (3)
  • 38-41: The instructions for downloading the polkadot-sdk version v1.5.0 and related files have been updated correctly. This ensures that users are working with the latest versions of the required software for end-to-end testing.
  • 59-59: The Git checkout command for the polkadot repository has been updated to version v1.5.0. This change ensures that users are using the correct version of the software for their testing environment.
  • 69-69: The Git checkout command for the cumulus repository has been updated to version v1.5.0. This update aligns with the need to use consistent and up-to-date versions of the software for end-to-end testing.
src/server/routes/actions.spec.ts (4)
  • 79-79: The parameter name in the assertion has been correctly updated to "captchaResponse" to reflect the change in the request payload. This change aligns with the migration to a more flexible captcha handling system.
  • 88-90: The request payload in the test case has been updated to use "captchaResponse" instead of "recaptcha". This change is consistent with the broader migration efforts and ensures that the test cases reflect the current implementation.
  • 101-103: The request payload and assertion in the error reporting test case have been updated to use "captchaResponse". This ensures that the test cases are aligned with the updated parameter naming convention.
  • 111-111: The request payload in the internal error test case has been updated to use "captchaResponse". This change maintains consistency across all test cases and aligns with the migration to a new captcha system.
src/dripper/DripRequestHandler.spec.ts (6)
  • 5-6: The introduction of Procaptcha and Recaptcha imports supports the integration of the new captcha system. This change is essential for enabling the test cases to work with different captcha providers.
  • 8-8: The introduction of the Captcha type, which encompasses both Procaptcha and Recaptcha, is a good practice. It provides a unified type for handling different captcha services, enhancing the flexibility of the test setup.
  • 18-18: Renaming the variable to captchaProvider and defining it as a type of Captcha is a positive change. It generalizes the captcha handling mechanism, allowing for the integration of different captcha services in the test cases.
  • 28-28: The instantiation of DripRequestHandler with captchaProvider correctly reflects the changes made to support multiple captcha systems. This ensures that the test setup aligns with the updated implementation of the DripRequestHandler.
  • 100-100: Updating the property name in the request object to captchaResponse aligns with the broader migration to a more flexible captcha handling system. This change ensures that the test cases reflect the current implementation accurately.
  • 149-150: The test case for validating the captcha response has been updated to use captchaResponse. This ensures that the test cases are aligned with the updated parameter naming convention and accurately test the captcha validation logic.
src/dripper/polkadot/PolkadotActions.ts (2)
  • 44-44: The replacement of waitReady with cryptoWaitReady is a significant change. Ensure that all dependencies and usages of the cryptoWaitReady function are correctly handled and that there are no side effects or issues with the initialization of the Polkadot API or keyring.
  • 99-101: The update to the logging message in the teleportTokens method to include more detailed information about the transaction is a good improvement for clarity and debugging purposes. However, ensure that logging sensitive information is avoided to maintain security.
src/test/setupE2EProcaptcha.ts (5)
  • 12-36: The setupProcaptcha function correctly sets up the Prosopo Procaptcha contract, registers a provider, sets a dataset, and registers an app site key. Ensure that the contract deployment and registration processes are thoroughly tested to prevent any issues during runtime.
  • 39-59: The deployProcaptchaContract function deploys the Prosopo Captcha contract. Ensure that the contract deployment is successful and that the contract address is correctly returned. It's also important to verify that the contract ABI and wasm bytecode are correctly loaded and used.
  • 63-79: The procaptchaProviderRegister function registers a Procaptcha provider. Ensure that the provider registration arguments are correctly formatted and that the registration transaction is successful. Pay attention to the hardcoded value for the provider's URL and the minimum value required for a captcha provider to be active.
  • 82-101: The procaptchaProviderSetDataset function sets the dataset for the Procaptcha provider. Ensure that the dataset IDs are correctly hashed and that the dataset setting transaction is successful. It's crucial to verify that the dataset IDs match the expected values.
  • 104-118: The procaptchaAppRegister function registers an app with the Prosopo Captcha contract. Ensure that the app registration is successful and that the site key and payee are correctly handled. It's important to verify that the minimum value for an app to be active is correctly set.
src/bot/index.ts (1)
  • 16-18: The addition of a check for a valid captcha provider before initializing the dripRequestHandler instance is a good practice to ensure that the bot is configured with a supported captcha provider. This prevents runtime errors due to invalid configuration.
src/test/setupE2E.ts (2)
  • 90-137: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [70-118]

The modifications to the setup function to include the setup for the Prosopo Procaptcha are comprehensive, covering the deployment of the contract, registration of providers and apps, and setting of datasets. Ensure that the setup process is correctly implemented and that all necessary parameters are correctly passed and handled.

  • 134-134: The addition of the procaptchaContainer to the teardown function ensures that the Procaptcha mock provider container is correctly stopped after the end-to-end tests. This is important for cleaning up resources and avoiding potential conflicts in subsequent test runs.
src/faucet.e2e.ts (5)
  • 7-7: The import of RandomProvider from @prosopo/captcha-contract introduces a dependency on the Prosopo captcha system. Ensure that the version of @prosopo/captcha-contract used is compatible with the rest of the project's dependencies and that it has been added to the project's package.json.
  • 31-32: The declaration of procaptchaDetails without immediate initialization suggests it will be set up later, likely in a setup function. Ensure that procaptchaDetails is properly initialized before use in tests to avoid runtime errors.
  • 66-72: The beforeAll setup now includes initialization for rococoContractsParachainApi and PROSOPO_SITE_KEY, which is crucial for connecting to the Prosopo captcha service. Ensure that the setup function correctly initializes these components and handles any potential errors during the setup process to prevent flaky tests.
  • 89-89: Disconnecting from rococoContractsParachainApi in the afterAll cleanup function is good practice to release resources. Verify that all connections established during tests are properly closed to avoid resource leaks.
  • 210-214: The use of procaptchaGetRandomProvider to obtain a RandomProvider instance for captcha verification introduces a dependency on external services. Ensure that the network and contract details used here are appropriate for the test environment and that any network calls are mocked or handled in a way that does not introduce flakiness to the tests.
client/tests/faucet.ts (4)
  • 5-5: The update to the FormSubmit type to use captchaResponse instead of recaptcha reflects the migration to a more generic captcha handling approach. Ensure that all references to the old recaptcha field are updated accordingly in the codebase to prevent type errors.
  • 9-10: The introduction of the CaptchaProvider type is a good practice for maintaining type safety and clarity in the code. It helps ensure that only supported captcha providers are used throughout the tests.
  • 105-119: The getCaptchaProvider method is a clean way to fetch the captcha provider from the configuration. Ensure that the configuration is correctly set up in the test environment to provide the expected captcha provider value. Additionally, consider handling the case where the configuration might return an unexpected value more gracefully.
  • 131-138: The tests now correctly pass the captcha provider configuration to getFormElements. This is crucial for ensuring that the tests interact with the correct captcha system. Verify that the captcha provider is correctly determined in all test environments to prevent test failures due to configuration issues.


const randomAddress = () => createTestKeyring().addFromSeed(randomAsU8a(32)).address;
const sha256 = (x: string) => crypto.createHash("sha256").update(x, "utf8").digest("hex");

describe("Faucet E2E", () => {
const PARACHAIN_ID = 1000; // From the zombienet config.
const PROSOPO_SITE_KEY = "5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM"; // procaptcha demo account (zero address)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PROSOPO_SITE_KEY constant is hard-coded. For production or broader testing environments, consider fetching such sensitive information from environment variables or a secure configuration management system to avoid exposing keys in the source code.

- const PROSOPO_SITE_KEY = "5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM";
+ const PROSOPO_SITE_KEY = process.env.PROSOPO_SITE_KEY;

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
const PROSOPO_SITE_KEY = "5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM"; // procaptcha demo account (zero address)
const PROSOPO_SITE_KEY = process.env.PROSOPO_SITE_KEY;

Comment on lines +11 to +53
const getFormElements = async (page: Page, captchaProvider: "recaptcha" | "procaptcha", getCaptcha = false) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
let captcha: Locator = {} as Locator;
if (getCaptcha) {
// ?: Hack. We need to wait for the frame to load and then invade it.
await page.reload();
const captchaFrame = await new Promise<Frame>((resolve, reject) => {
let i = 0;
// function that waits for the frame and timeouts after 3 seconds
// FIXME consider "until" from "@eng-automation/js"?
// eslint-disable-next-line no-restricted-syntax
(function waitForFrame() {
const captchaFrames = page.frames().filter((f) => f.url().includes("https://www.google.com/recaptcha/api2/"));
if (captchaFrames.length > 0) {
return resolve(captchaFrames[0]);
} else {
i++;
if (i > 10) {
reject(new Error("Timeout"));
if (captchaProvider === "recaptcha") {
// ?: Hack. We need to wait for the frame to load and then invade it.
await page.reload();
const captchaFrame = await new Promise<Frame>((resolve, reject) => {
let i = 0;
// function that waits for the frame and timeouts after 3 seconds
// FIXME consider "until" from "@eng-automation/js"?
// eslint-disable-next-line no-restricted-syntax
(function waitForFrame() {
const captchaFrames = page.frames().filter((f) => f.url().includes("https://www.google.com/recaptcha/api2/"));
if (captchaFrames.length > 0) {
return resolve(captchaFrames[0]);
} else {
i++;
if (i > 10) {
reject(new Error("Timeout"));
}
}
}
setTimeout(waitForFrame, 300);
})();
});
captcha = captchaFrame?.locator("#recaptcha-anchor") as Locator;
setTimeout(waitForFrame, 300);
})();
});
captcha = captchaFrame?.locator("#recaptcha-anchor") as Locator;
} else if (captchaProvider === "procaptcha") {
const testAccount = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice's address
const testSiteKey = "5C4hrfjw9DjXZTzV3MwzrrAr9P1MJhSrvWGWqi1eSuyUpnhM"; // Mock site key
const testProvider = "https://mockprovider.prosopo.io"; // Mock provider

// Tell the page that a captcha provider has previously been used and inject the mock provider
await page.evaluate((provider) => localStorage.setItem("@prosopo/provider", provider), testProvider);

// Mock the verify api call and inject Alice's address before clicking the captcha
await page.route("*/**/v1/prosopo/provider/verify", async (route) => {
const json = { user: testAccount, dapp: testSiteKey };
await route.continue({ postData: json });
});
captcha = page.locator("#captcha_element input[type='checkbox']");
} else {
throw new Error("Unknown captcha provider");
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The modifications to the getFormElements function to handle different captcha providers are comprehensive and include handling for both recaptcha and procaptcha. Ensure that the logic for each captcha provider is thoroughly tested, especially the new procaptcha logic, which includes mocking API calls and setting local storage items. Consider abstracting the captcha-specific logic into separate functions for better readability and maintainability.

@paritytech-stg paritytech-stg deleted a comment from cla-bot-2021-stg bot Feb 23, 2024
@Bullrich Bullrich closed this Mar 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

PoC: Migrate to Prosopo
2 participants