diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..4b89e7f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,365 @@ +# Reclaim Protocol Documentation - Complete Reference Guide + +This document provides a comprehensive overview of the entire Reclaim Protocol documentation, covering all SDKs, integration methods, and technical details found in the `/content/docs` directory. + +## 🎯 Overview + +Reclaim Protocol is a privacy-preserving identity and data verification protocol that enables users to prove facts about their online activity without revealing sensitive information. The protocol supports **2500+ data sources** and provides SDKs for web, mobile, and blockchain platforms. + +### Key Features +- **Zero-Knowledge Proofs**: Verify data without exposing credentials +- **Cross-Platform SDKs**: Web, Mobile (iOS/Android/React Native/Flutter), and 15+ blockchains +- **Privacy-First**: End-to-end encryption with no credential storage +- **Seamless UX**: App Clips/Instant Apps - no installation required + +## πŸ”‘ Getting Started + +### 1. Create Application +1. Register at [dev.reclaimprotocol.org](https://dev.reclaimprotocol.org) +2. Create new application with name, description, and logo +3. Copy `APP_ID` and `APP_SECRET` (⚠️ Secret shown only once) +4. Add providers to your application +5. Note down `PROVIDER_ID` for each provider + +### 2. Core Concepts + +#### **Proofs** +- Cryptographic evidence of user's online activity +- Generated through secure TLS communication +- Verifiable without revealing sensitive data + +#### **Attestors** +- Opaque proxies between users and target servers +- Cannot decrypt user data (end-to-end TLS encryption) +- Verify and sign claims without accessing sensitive info + +#### **Providers** +- Define what to verify and how +- Components: `loginUrl`, `requestData`, `responseMatches`, `responseRedactions` +- Create custom providers via DevTool + +#### **Verifier Apps** +- Native mobile apps via App Clips (iOS) / Instant Apps (Android) +- No installation required - access via URL +- Handle proof generation seamlessly + +## 🌐 Web SDK Integration + +### Frontend (React/JS) + +#### Method 1: `triggerReclaimFlow()` (Recommended) +```javascript +import { ReclaimProofRequest } from '@reclaimprotocol/js-sdk'; + +const handleVerification = async () => { + const reclaimProofRequest = await ReclaimProofRequest.init(APP_ID, APP_SECRET, PROVIDER_ID); + + // Auto-detects environment (extension/QR/mobile) + await reclaimProofRequest.triggerReclaimFlow(); + + await reclaimProofRequest.startSession({ + onSuccess: (proofs) => { + console.log('Verification successful:', proofs); + }, + onError: (error) => { + console.error('Verification failed', error); + } + }); +}; +``` + +#### Method 2: Manual QR Code +```javascript +const requestUrl = await reclaimProofRequest.getRequestUrl(); +// Display as QR code or link +``` + +### Backend Verification + +#### Node.js/Express +```javascript +import { ReclaimProofRequest } from '@reclaimprotocol/js-sdk'; + +app.post('/request-proof', async (req, res) => { + const request = await ReclaimProofRequest.init(APP_ID, APP_SECRET, PROVIDER_ID); + request.setCallbackUrl(`${BASE_URL}/receive-proofs`); + + const { requestUrl, statusUrl } = await request.createVerificationRequest(); + res.json({ requestUrl, statusUrl }); +}); + +app.post('/receive-proofs', async (req, res) => { + const { claimData } = req.body; + const isValid = await ReclaimProofRequest.verifyProof(claimData); + // Process verified data +}); +``` + +#### Python/FastAPI +```python +from reclaim_python_sdk import ReclaimProofRequest + +@app.post("/request-proof") +async def request_proof(): + request = ReclaimProofRequest(APP_ID, APP_SECRET, PROVIDER_ID) + request.set_callback(f"{BASE_URL}/receive-proofs") + + request_url = await request.get_request_url() + status_url = request.get_status_url() + return {"requestUrl": request_url, "statusUrl": status_url} +``` + +## πŸ“± Mobile SDKs + +### React Native + +#### Installation (Expo) +```bash +npx expo install @reclaimprotocol/inapp-rn-sdk +``` + +Add to `app.json` plugins: +```json +"plugins": [ + "@reclaimprotocol/inapp-rn-sdk" +] +``` + +#### Usage +```javascript +import { ReclaimVerification } from '@reclaimprotocol/inapp-rn-sdk'; + +const handleVerify = async () => { + const sessionId = await ReclaimVerification.startVerification({ + applicationId: APP_ID, + applicationSecret: APP_SECRET, + providerId: PROVIDER_ID, + }); + + // Handle success/failure +}; +``` + +### iOS (Swift) + +#### Installation +```swift +// Swift Package Manager +.package(url: "https://github.com/reclaimprotocol/reclaim-inapp-ios-sdk.git", from: "0.3.0") + +// CocoaPods +pod 'ReclaimInAppSdk', '~> 0.3.0' +``` + +#### Performance Fix Required +Add to Xcode scheme environment variables: +- Key: `GODEBUG` +- Value: `asyncpreemptoff=1` + +### Android (Kotlin) + +#### Setup +```groovy +// settings.gradle +repositories { + maven { url "https://reclaim-inapp-sdk.s3.ap-south-1.amazonaws.com/android/0.3.0/repo" } +} + +// build.gradle +implementation "org.reclaimprotocol:inapp_sdk:0.3.0" +``` + +#### AndroidManifest.xml +```xml + + + +``` + +## ⛓️ Blockchain Integration + +### Supported Networks +- **EVM**: Ethereum, Polygon, Arbitrum, Optimism, BSC, Base, etc. +- **Non-EVM**: Solana, Cosmos, NEAR, Polkadot, Sui, Cardano, Stellar, Mina, and more + +### Solidity Example +```solidity +import "@reclaimprotocol/verifier-solidity-sdk/contracts/Reclaim.sol"; +import "@reclaimprotocol/verifier-solidity-sdk/contracts/Addresses.sol"; + +contract Attestor { + address public reclaimAddress; + + constructor() { + reclaimAddress = Addresses.ETHEREUM; // Or other network + } + + function verifyProof(Reclaim.Proof memory proof) public view { + Reclaim(reclaimAddress).verifyProof(proof); + // Extract context fields if needed + string memory steamId = Reclaim(reclaimAddress) + .extractFieldFromContext(proof.claimInfo.context, '"SteamId":"'); + } +} +``` + +## πŸ” zkFetch SDK + +Generate proofs of HTTP responses with privacy preservation. + +### Basic Usage +```javascript +import { ReclaimClient } from '@reclaimprotocol/zk-fetch'; + +const client = new ReclaimClient(APP_ID, APP_SECRET); + +// Public endpoint +const proof = await client.zkFetch('https://api.example.com/data', { + method: 'GET', + headers: { accept: 'application/json' } +}); + +// Private endpoint with hidden auth +const proofPrivate = await client.zkFetch( + 'https://api.example.com/private', + { method: 'GET' }, // Public options + { headers: { apiKey: 'secret-key' } } // Private options (hidden) +); +``` + +### Advanced Features +```javascript +// Response matching and redaction +const proof = await client.zkFetch(url, publicOpts, { + responseMatches: [{ + type: 'regex', + value: '\\{"price":(?[\\d\\.]+)\\}' + }], + responseRedactions: [{ + jsonPath: '$.sensitive_data' + }] +}); + +// Verify and transform for blockchain +const isValid = await Reclaim.verifySignedProof(proof); +const onchainProof = Reclaim.transformForOnchain(proof); +``` + +## 🎨 OAuth Integration + +### React OAuth SDK +```javascript +import { useReclaimAuth } from '@reclaimprotocol/reclaim-react-sdk'; + +function App() { + const { user, loading, error, signIn, signOut } = useReclaimAuth(); + + const handleAuth = async () => { + await signIn({ + clientId: CLIENT_ID, + redirectUri: REDIRECT_URI, + providers: ['google-login', 'github-login'] + }); + }; +} +``` + +## πŸ€– AI Agent Integration + +Email-based verification with A2A protocol compatibility: + +```javascript +// Send verification email +await agent.sendVerificationEmail({ + to: 'user@example.com', + verificationType: 'google-login' +}); + +// Check status +const status = await agent.checkVerificationStatus(verificationId); +``` + +## πŸ› οΈ Advanced Features + +### Verification Options +```javascript +{ + canDeleteCookiesBeforeVerificationStarts: true, // Clear session storage + canUseAttestorAuthenticationRequest: false, // Authentication request + claimCreationType: 'standalone', // or 'meChain' + canAutoSubmit: true, // Auto-submit proof + isCloseButtonVisible: true // Show close button +} +``` + +### Provider Structure +```javascript +{ + loginUrl: 'https://example.com/login', + requestData: [{ + url: 'https://api.example.com/user', + method: 'GET', + responseMatches: [{ + type: 'contains', + value: '"email":"{{email}}"' + }], + responseRedactions: [{ + jsonPath: '$.password', + regex: 'token=[^&]*' + }] + }] +} +``` + +## 🚨 Security Considerations + +1. **Never expose APP_SECRET in frontend code** +2. **Always verify proofs server-side in production** +3. **Use environment variables for credentials** +4. **Implement proper error handling** +5. **Set appropriate webhook URLs for async flows** + +## πŸ“š Resources + +- **Developer Portal**: [dev.reclaimprotocol.org](https://dev.reclaimprotocol.org) +- **Provider Explorer**: [2500+ providers](https://dev.reclaimprotocol.org/explore) +- **Telegram Support**: [t.me/protocolreclaim](https://t.me/protocolreclaim) +- **Technical Blog**: [blog.reclaimprotocol.org](https://blog.reclaimprotocol.org) +- **GitHub**: [github.com/reclaimprotocol](https://github.com/reclaimprotocol) +- **Security Analysis**: [ePrint 2024/733](https://eprint.iacr.org/2024/733) + +## 🎯 Common Use Cases + +1. **Identity Verification**: Education, employment, professional credentials +2. **Financial Data**: Credit scores, income verification, accredited investor status +3. **Loyalty/Reputation**: Shopping history, platform activity, gaming achievements +4. **On-chain Oracles**: Bringing web2 data to smart contracts +5. **Access Control**: Gated content based on off-chain activity + +## πŸ’‘ Best Practices + +1. **Development Flow**: + - Start with frontend quickstart + - Implement backend verification + - Add error handling and retry logic + - Test with multiple providers + +2. **Production Checklist**: + - βœ… Backend proof verification + - βœ… Secure credential management + - βœ… Webhook implementation + - βœ… Error tracking + - βœ… Rate limiting + +3. **User Experience**: + - Show clear verification status + - Provide fallback options + - Handle edge cases gracefully + - Optimize for mobile experience + +This documentation represents the complete Reclaim Protocol ecosystem as documented in the `/content/docs` directory. Each section provides entry points into specific implementation details while maintaining the overall context of the protocol's capabilities and best practices. \ No newline at end of file diff --git a/content/docs/advance-options/attestor-auth.mdx b/content/docs/advance-options/attestor-auth.mdx deleted file mode 100644 index 1bc2df2..0000000 --- a/content/docs/advance-options/attestor-auth.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Attestor Authentication -description: Reclaim Protocol's InApp SDKs setup when using an attestor with authentication ---- - -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; - -# Get Started - -A private attestor can have authentication enabled which blocks all un-authenticated connections and can also be used to limit the hosts that can be connected to. InApp SDKs can be configured to use another attestor and include an auth request in the claim sent to this attestor. - -Read more about [attestors authentication here](https://github.com/reclaimprotocol/attestor-core/blob/main/docs/run-server.md#enabling-authentication). - -## Basic Usage - -An auth request can be created anywhere, even on your server. JS library @reclaimprotocol/attestor-core from npm can be used for creating an auth request. - -```typescript -import { createAuthRequest, B64_JSON_REPLACER } from '@reclaimprotocol/attestor-core' - -// this can happen on another server, on the client or anywhere you'd -// like -const authRequest = await createAuthRequest( - { - // optional user ID -- to identify the user - // all logs on the backend will be tagged with this - id: 'optional-user-id', - // only allow the user to tunnel requests to one of - // these hosts - hostWhitelist: ['github.com', 'example.com'] - }, - keyPairs.privateKey -) -const yourAttestorAuthRequest = JSON.stringify( - authRequest, - B64_JSON_REPLACER, - 2 -) -console.info({ yourAttestorAuthRequest }); -``` - -An auth request looks like this: - -```json -{ - "data": { - "userId": "optional-user-id", - "hostWhitelist": ["api.abcd.xyz"] - }, - "signature": { - "type": "uint8array", - "value": "base64-encoded-signature" - } -} -``` - -This can be used in the `setVerificationOptions` method of the InApp SDK, which allows you to set a callback for providing an auth request to the attestor. - - - -```typescript tabs="Typescript" -const reclaimVerification = new ReclaimVerification(); - -// This is how you may be using a different attestor with overrides -await reclaimVerification.setOverrides({ - featureOptions: { - // overridden attestor browser rpc url - attestorBrowserRpcUrl: 'https://myattestor.example.org/browser-rpc', - // other overrides (removed for brevity) - }, -}); - -// Provide a callback to provide attestor auth request. -await reclaimVerification.setVerificationOptions({ - fetchAttestorAuthenticationRequest: async (providerInformationJsonString: string) => { - // sample attestor auth request - return JSON.stringify({ - "data": { - "createdAt": 1741648166, - "expiresAt": 1741649066, - "id": "optional-user-id", - "hostWhitelist": [ - "github.com", - "example.com" - ] - }, - "signature": { - "type": "uint8array", - "value": "gSCbBMZSdNJjrxGUTPoERj5S8jtkwQEnGWmmMXx+j3wrd7pspRkfhE96DauFQTVcp+ErB7zWaBDAWwThOu4Fkxw=" - } - }); - }, -}); -``` - -```kotlin tabs="Kotlin" -ReclaimVerification.setOverrides( - context = context, - featureOptions = ReclaimOverrides.FeatureOptions( - // overridden attestor browser rpc url - attestorBrowserRpcUrl = "https://myattestor.example.org/browser-rpc" - // other overrides (removed for brevity) - ) -) { result -> - result - .onSuccess { - Log.d("MainActivity", "Reclaim Overrides set") - } - .onFailure { e -> - Log.e("MainActivity", "Could not set overrides", e) - } -} - -ReclaimVerification.setVerificationOptions( - context = context, - options = ReclaimVerification.VerificationOptions( - attestorAuthRequestProvider = object : ReclaimVerification.VerificationOptions.AttestorAuthRequestProvider { - override fun fetchAttestorAuthenticationRequest( - reclaimHttpProvider: Map, - callback: (Result) -> Unit - ) { - // sample attestor auth request - callback(Result.success(""" - { - "data": { - "createdAt": 1741648166, - "expiresAt": 1741649066, - "id": "optional-user-id", - "hostWhitelist": [ - "github.com", - "example.com" - ] - }, - "signature": { - "type": "uint8array", - "value": "gSCbBMZSdNJjrxGUTPoERj5S8jtkwQEnGWmmMXx+j3wrd7pspRkfhE96DauFQTVcp+ErB7zWaBDAWwThOu4Fkxw=" - } - } - """.trimIndent())) - } - } - ) -) { result -> - result - .onSuccess { - Log.d("MainActivity", "Reclaim Verification options set") - } - .onFailure { e -> - Log.e("MainActivity", "Could not set verification options", e) - } -} -``` - -```swift tabs="Swift" -// This is how you may be using a different attestor with overrides -try await ReclaimVerification.setOverrides( - featureOptions: .init( - // overridden attestor browser rpc url - attestorBrowserRpcUrl: "https://myattestor.example.org/browser-rpc" - // other overrides (removed for brevity) - ) -) - -class AttestorAuthRequestProviderImpl : ReclaimVerification.VerificationOptions.AttestorAuthRequestProvider { - func fetchAttestorAuthenticationRequest( - reclaimHttpProvider: [AnyHashable?: (any Sendable)?], - completion: @escaping (Result) -> Void - ) { - // sample attestor auth request - completion(.success(""" - { - "data": { - "createdAt": 1741648166, - "expiresAt": 1741649066, - "id": "optional-user-id", - "hostWhitelist": [ - "github.com", - "example.com" - ] - }, - "signature": { - "type": "uint8array", - "value": "gSCbBMZSdNJjrxGUTPoERj5S8jtkwQEnGWmmMXx+j3wrd7pspRkfhE96DauFQTVcp+ErB7zWaBDAWwThOu4Fkxw=" - } - } - """)) - } -} - -try await ReclaimVerification.setVerificationOptions(options: .init( - attestorAuthRequestProvider: AttestorAuthRequestProviderImpl() -)) -``` - - diff --git a/content/docs/advance-options/js-injections/index.mdx b/content/docs/advance-options/js-injections/index.mdx deleted file mode 100644 index 0cf04a7..0000000 --- a/content/docs/advance-options/js-injections/index.mdx +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: JS Injections -description: Understanding JavaScript Injections in Providers ---- - -## What are JS Injections? - -When you hear the word "injection," you might think, "Wait, is this some kind of attack?" or "What's going on here?" But actually, injections in the world of JavaScript are far from being anything harmful. They're just simple code snippets that help with tasks we deal with every day like manipulating the DOM or making network calls. So, there's no need to worry. In fact, injections are just another tool that makes our provider more efficient. - -## Important Note - -**Injections in providers are subject to Admin approval. The provider will be reviewed and approved before it can be published. Only after approval will it become available for use.** - -**We will discuss potential security risks associated with using providers that include injections in the Advanced Section** - -## When to Use JS Injections - -### 1. Programmatic Navigation - -If you want to navigate to the proof generation page automatically so users don't have to click around and do it manually. This is a great use for a JS injection. - -### 2. Handling Large Payloads - -If you're dealing with a large payload and need to include it as part of your proof, this is where injections come in handy. For example: - -- Handling paginated responses -- Retrieving all orders from the last 3 months -- Pulling a user's complete ride history - -When building a provider, injections allow you to add powerful interactivity and automation capabilities. They serve two main purposes: - -1. **Automating User Navigation**: Injections can handle page navigation automatically, eliminating the need for users to click through multiple pages manually. This creates a smoother, more streamlined experience. - -2. **Capturing Page Data**: They can automatically collect and include public data present on web pages into your proof, making data gathering more efficient. - -These capabilities are especially valuable when dealing with complex workflows or when you need to gather data from multiple sources on a website. diff --git a/content/docs/advance-options/js-injections/large-payload.mdx b/content/docs/advance-options/js-injections/large-payload.mdx deleted file mode 100644 index 27d05cf..0000000 --- a/content/docs/advance-options/js-injections/large-payload.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -title: Large Payload -description: Handling Large Payloads in Providers ---- - -**Adding Large Payload as Public Data to the Proof Object** - -In the previous example, we saw how we can enable programmatic navigation. Now, let's explore how we can add large payloads as public data to the proof object. - -**Wait, What is Public Data?** - -You might be wondering, "What exactly is public data?" Well, here's the context: - -Zero-knowledge proofs (ZKPs) come with certain limitations. These proofs are compute-intensive operations, and in many cases, they are executed directly on the user's device like a phone. There are no Reclaim servers in between the process. The phone has limited memory and cannot handle processing large amounts of data all at once. - -This is where **public data** comes to the rescue. - -**Use Case: Large Payload Example** - -Let's say you are working with a large response, such as Swiggy order details. If you try to include all that data in the proof, the user might have to wait for several minutes just for the proof to generate. Instead of including the entire payload, you can verify one specific piece of data and store the rest as public data. - -The flow would look like this: - -- You would verify a small piece of information, such as the `order ID` or the `total amount` of a specific order. -- The rest of the data like the full order history would be added to the **`public` parameters** of the proof. **While the proof only contains a verified subset, you can still be confident that the entire payload originates from the correct source.** - -In other words, the proof could verify a particular order's details (e.g., order ID, total price), but the full order history would be publicly available data. We will also have an attestation to confirm that the source of the data (in this case, Swiggy's API) is legitimate and trustworthy. - -**Example Code :** - -**Prerequisites** - -Before proceeding, it's assumed that you have some experience with **JavaScript DOM manipulation** or making **API calls**. If you're unfamiliar with these concepts, it's recommended to first familiarize yourself with the basics of interacting with web pages using JavaScript. - ---- - -### Step 1: Fetching Order Details in the Background - -There are two options for fetching order data: - -1. **From DOM Elements** - If the order details are already available in the page's HTML, you can extract them using DOM manipulation techniques. However, this method is less reliable because the HTML structure might change frequently. - -2. **From an Internal API** - A more reliable approach is to fetch the order details using an internal API that returns the order data. API responses are usually more stable than the structure of HTML elements. - -**Why Use API Calls?** - -- **Stability**: The API response structure is less likely to change, ensuring your code remains functional over time. -- **Efficiency**: APIs provide structured data, making it easier to parse and use compared to DOM manipulation. - -The snippet below shows how to fetch Swiggy order details using an API call: - -```jsx -async function fetchOrderDetails() { - try { - // Swiggy's internal API (note: token or user ID requirements may apply) - const response = await fetch('https://www.swiggy.com/dapi/order/all?order_id=', { - headers: { - __fetch_req__: 'true', - accept: '*/*', - 'accept-language': 'en-GB,en;q=0.5', - 'content-type': 'application/json', - 'if-none-match': 'W/"1219b-rbUuzLmo540FSk8g0KzJG+MnMEs"', - priority: 'u=1, i', - 'sec-ch-ua': '"Chromium";v="130", "Brave";v="130", "Not?A_Brand";v="99"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"macOS"', - 'sec-fetch-dest': 'empty', - 'sec-fetch-mode': 'cors', - 'sec-fetch-site': 'same-origin', - 'sec-gpc': '1', - }, - referrer: 'https://www.swiggy.com/my-account', - method: 'GET', - mode: 'cors', - credentials: 'include', // Important - }); - - const orders = await response.json(); - return orders; - } catch (error) { - console.error('Error fetching order details:', error); - } -} -``` - ---- - -### Step 2: Adding Public Data to the Proof Object - -After fetching the order details, you need to add this data to the proof object and then navigate to the proof generation page. - -```jsx -function navigateToProofPage(orderData) { - // Inject order data as public data - window.flutter_inappwebview.callHandler('publicData', JSON.stringify(orderData)); - - // Mark JS injection as completed - window.reclaimFetchInjected = true; - - // Navigate to the proof generation page - window.location.href = 'https://www.swiggy.com/my-account'; -} - -// Main function to control the process -async function handleProofGeneration() { - // Check if the injection has already occurred - if (window.reclaimFetchInjected) { - console.log('JS already injected, skipping.'); - return; - } - - showModal(); // Show the loading modal while fetching data - - const orderData = await fetchOrderDetails(); - if (orderData) { - navigateToProofPage(orderData); - } -} - -// Run the function periodically (every 3 seconds) -setInterval(handleProofGeneration, 3000); -``` - -To include the fetched order data as **public data** in the proof object, you can use the `window.flutter_inappwebview.callHandler()` function. This method allows you to send the data to the native layer of the app for processing. - -`*// Assuming 'orderData' contains the order details fetched in Step 1*` - -`window.flutter_inappwebview.callHandler('publicData', JSON.stringify(orderData));` - -`publicData - is the keyword` - -**Navigating to the Proof Generation Page** - -Now, you need to navigate to the page where the proof will actually be generated. In the case of Swiggy, the order data is available on the https://www.swiggy.com/my-account page. - -`window.location.href = 'https://www.swiggy.com/my-account';` - -**Why navigate to a different page?** - -**Reclaim operates based on response matching. When you are working with proof generation, the response from the target page (in this case, the Swiggy account page) must match the specific key pointers you've defined for the provider.** - -**For instance, when generating the proof for Swiggy order details, you need to navigate to the my-account page because this is where the actual order data resides. The API or DOM response from that page will be compared with the pointers you've defined during the provider setup (e.g., order ID, total amount). Only if the response matches the defined pointers, the proof generation will be triggered.** - -**3- Showing the Loading Modal (Optional) This is for the better UX.** - -When the script is running, you may want to show a loading modal to inform the user that data is being fetched and processed. Here's the function to show a loading modal: - -```jsx -function showModal() { - let modal = document.createElement('div'); - modal.id = 'proofGenerationModal'; - modal.style.display = 'none'; - modal.style.position = 'fixed'; - modal.style.zIndex = '1'; - modal.style.paddingTop = '100px'; - modal.style.left = '0'; - modal.style.top = '0'; - modal.style.width = '100%'; - modal.style.height = '100%'; - modal.style.overflow = 'auto'; - modal.style.backgroundColor = 'rgba(0,0,0,0.4)'; - modal.innerHTML = ` -
-

Fetching data

-

Please wait

-
-
- - `; - document.body.appendChild(modal); - document.getElementById('proofGenerationModal').style.display = 'block'; -} -``` - -**Summary:** - -**Fetching Order Data**: - -- The fetchOrderDetails() function fetches the order data from the Swiggy API. You can adapt this for any other API or service as needed. - -**Loading Modal**: - -- The showModal() function creates and displays a loading modal to inform users that data is being processed. - -**Injecting Data**: - -- The navigateToProofPage() function injects the fetched order data into the proof generation process and navigates to the page where the proof is generated. - -**JS Injection Tracking**: - -- The window.reclaimFetchInjected flag ensures that the JS injection only occurs once. This flag is set to true after the first injection to prevent redundant injections during subsequent checks. - -**Full Code:** - -```jsx -// Function to fetch order details (can be adapted for other APIs) -async function fetchOrderDetails() { - try { - const response = await fetch('https://www.swiggy.com/dapi/order/all?order_id=', { - headers: { - __fetch_req__: 'true', - accept: '*/*', - 'accept-language': 'en-GB,en;q=0.5', - 'content-type': 'application/json', - 'if-none-match': 'W/"1219b-rbUuzLmo540FSk8g0KzJG+MnMEs"', - priority: 'u=1, i', - 'sec-ch-ua': '"Chromium";v="130", "Brave";v="130", "Not?A_Brand";v="99"', - 'sec-ch-ua-mobile': '?0', - 'sec-ch-ua-platform': '"macOS"', - 'sec-fetch-dest': 'empty', - 'sec-fetch-mode': 'cors', - 'sec-fetch-site': 'same-origin', - 'sec-gpc': '1', - }, - referrer: 'https://www.swiggy.com/my-account', - method: 'GET', - mode: 'cors', - credentials: 'include', - }); - const orders = await response.json(); - return orders; - } catch (error) { - console.error('Error fetching order details:', error); - } -} - -// Function to show loading modal -function showModal() { - let modal = document.createElement('div'); - modal.id = 'proofGenerationModal'; - modal.style.display = 'none'; - modal.style.position = 'fixed'; - modal.style.zIndex = '1'; - modal.style.paddingTop = '100px'; - modal.style.left = '0'; - modal.style.top = '0'; - modal.style.width = '100%'; - modal.style.height = '100%'; - modal.style.overflow = 'auto'; - modal.style.backgroundColor = 'rgba(0,0,0,0.4)'; - modal.innerHTML = ` -
-

Fetching data

-

Please wait

-
-
- - `; - document.body.appendChild(modal); - document.getElementById('proofGenerationModal').style.display = 'block'; -} - -// Function to navigate to the proof generation page after data is ready -function navigateToProofPage(orderData) { - window.flutter_inappwebview.callHandler('publicData', JSON.stringify(orderData)); // orderData is from fetchOrderDetails - window.reclaimFetchInjected = true; // set to true to prevent unnecessary calls - window.location.href = 'https://www.swiggy.com/my-account'; -} - -// Main function to handle the entire flow -async function handleProofGeneration() { - // Check if JS injection has already occurred - if (window.reclaimFetchInjected) { - console.log('JS already injected, skipping.'); - return; // Prevent multiple injections - } - - showModal(); // Show loading modal while fetching data - const orderData = await fetchOrderDetails(); // Fetch order data - if (orderData) { - navigateToProofPage(orderData); // Pass the data and navigate to proof generation page - } -} - -// Run the function periodically -setInterval(handleProofGeneration, 5000); // Check every 5 seconds -``` - -Proof Structure - -β€”β€”β€”β€”β€”β€”β€”β€”- - -```jsx -{ - "reclaimProofRequestConfig": "{ - \"applicationId\": \"\", - \"providerId\": \"\", - \"sessionId\": \"\", - \"context\": { - \"contextAddress\": \"\", - \"contextMessage\": \"\" - }, - \"publicData\": \"\", // This is where all of the data is injected - \"requestedProof\": { - \"url\": \"\", - \"parameters\": { - \"\": \"\", - \"\": \"\" - } - }, - \"appCallbackUrl\": \"\", - \"signature\": \"\", - \"timeStamp\": \"\" - }" -} -``` - -**Summary:** - -- **Public Data is Not a Hack:** It is meant to deliver public information, extracted directly from the webpage, that does not require the stringent verification process of the core proof. -- **Keep Verification Lean:** Only send critical elements into the zero-knowledge proof, while the bulk of the data is passed as public data. -- **Improved Performance:** By separating public data from the verification-relevant data, devices with limited resources (like mobile phones) can operate more efficiently. - -For more production examples, please visit our [GitHub repository](https://github.com/Koushith/Nerdy-JS-Injections). - ---- diff --git a/content/docs/advance-options/js-injections/meta.json b/content/docs/advance-options/js-injections/meta.json deleted file mode 100644 index dc4ca8e..0000000 --- a/content/docs/advance-options/js-injections/meta.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "title": "js-injections", - "pages": [ - "programmatic-navigation", - "large-payload", - "security-risks" - ] -} \ No newline at end of file diff --git a/content/docs/advance-options/js-injections/programmatic-navigation.mdx b/content/docs/advance-options/js-injections/programmatic-navigation.mdx deleted file mode 100644 index a84ba27..0000000 --- a/content/docs/advance-options/js-injections/programmatic-navigation.mdx +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Programmatic Navigation -description: Understanding Programmatic Navigation in Providers ---- - -# Programmatic Navigation - -## Overview - -Programmatic navigation uses DOM manipulation to automate user interactions on web pages. In Reclaim, this is particularly important for proof generation - the API needs specific data that can only be accessed on certain pages. - -### Why Use Programmatic Navigation? - -When generating proofs, the API response must match specific key pointers defined during provider creation. For example, with a Twitter username proof: - -- The user must reach their profile page -- Twitter's API needs to fetch the profile information - -## Implementation Example - -Here's a code snippet that automatically navigates to a user's Twitter profile: - -```js -const pageCheck = () => { - // Check if on Twitter home page - if ( - window.location.href?.includes('https://x.com/home') || - window.location.href?.includes('https://twitter.com/home') - ) { - // Click profile icon to open menu - document.querySelector('button[data-testid="DashButton_ProfileIcon_Link"]').click(); - - // Wait briefly, then click profile link - setTimeout(() => { - document.querySelector('a.css-175oi2r.r-16y2uox.r-dnmrzs.r-o7ynqc.r-6416eg.r-1ny4l3l.r-1loqt21').click(); - }, 200); - } -}; - -// Check URL every 500ms -setInterval(pageCheck, 500); -``` - -You can test this by pasting it into your browser console (works for mobile view). - -## Code Breakdown - -1. **pageCheck Function** - - - Checks current URL - - Automates navigation to profile page - - Simulates necessary click events - -2. **URL Verification** - - - Checks for both `twitter.com/home` and `x.com/home` - - Uses optional chaining for safety - -3. **Click Simulation** - - - First click: Opens profile menu - - Second click: Navigates to profile page - - 200ms delay between clicks ensures proper loading - -4. **Continuous Checking** - - Runs every 500ms - - Ensures navigation happens as soon as possible - -## Important Considerations - -⚠️ **Warning**: This approach is sensitive to DOM changes. Twitter's HTML structure may update, potentially breaking the selectors. Regular maintenance is required to ensure continued functionality. - -**Alternative Approaches**: - -- XPath selectors -- Different timing intervals -- Custom event listeners - -The core concept remains the same: using JavaScript to manipulate the DOM and automate navigation. - -## Finding DOM Elements - -### Using Browser Developer Tools - -1. **Open Developer Tools** - - - Right-click on the element you want to target - - Select "Inspect Element" (or press F12) - - The element will be highlighted in the Elements panel - -2. **Finding Unique Selectors** - - Right-click on the highlighted element in the Elements panel - - Select "Copy" and then choose: - - "Copy selector" for CSS selectors - - "Copy XPath" for XPath selectors - -### Best Practices for Selecting Elements - -```js -// βœ… Good: Using data-testid (most stable) -document.querySelector('[data-testid="profile-button"]'); - -// βœ… Good: Using specific IDs -document.getElementById('profile-link'); - -// ⚠️ Caution: Using classes (may change frequently) -document.querySelector('.profile-button-class'); - -// ❌ Avoid: Complex CSS selectors (very fragile) -document.querySelector('div > span.menu-item:nth-child(2)'); -``` - -### Tips for Reliable Selectors - -- Look for `data-testid` attributes first - these are typically stable -- Use IDs when available - they're unique and reliable -- Avoid relying on class names alone - they often change with styling updates -- Test your selectors across different states (logged in/out, different themes) -- Consider mobile vs desktop layouts when selecting elements diff --git a/content/docs/advance-options/js-injections/security-risks.mdx b/content/docs/advance-options/js-injections/security-risks.mdx deleted file mode 100644 index 1e8d05f..0000000 --- a/content/docs/advance-options/js-injections/security-risks.mdx +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Security Risks ---- - -**Security Risks of Using Third-Party Providers with JS Injections** - -When using providers that include JavaScript injections, especially those created by third parties, it's important to be cautious about security. Here are the key risks to be aware of: - -**Risk of Malicious Code** - -JavaScript injections have full access to the webpage's DOM and can: - -- Read sensitive information (passwords, tokens, personal data) -- Send data to external servers -- Modify page content and behavior -- Access browser storage (cookies, localStorage) - -**Best Practices** - -- Always review the injection code before using a third-party provider -- Never paste JavaScript code from untrusted sources -- Verify the provider's reputation and source -- Test the provider in a safe environment before using in production - -> **Warning**: While we review providers before publishing, you should always verify the code yourself when using community-built providers with JS injections. Your application's security is your responsibility. diff --git a/content/docs/advance-options/js-injections/verification-options.mdx b/content/docs/advance-options/js-injections/verification-options.mdx deleted file mode 100644 index 82f06cf..0000000 --- a/content/docs/advance-options/js-injections/verification-options.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Verification Options -description: Customize the default verification flow with Reclaim Protocol's InApp SDKs ---- - -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; - -## Options API - -| Prop | Type | Description | -| ---------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------- | -| **`canDeleteCookiesBeforeVerificationStarts`** | boolean | This is enabled by default. Set false to persist sessions storage for the user. (This will be replaced with `canClearWebStorage` in an upcoming update) | -| **`canUseAttestorAuthenticationRequest`** | boolean | Enable the use of authentication request when starting a verification | -| **`claimCreationType`** | 'standalone' \| 'meChain' | The type of claim creation to use. Defaults to 'standalone'. | -| **`canAutoSubmit`** | boolean | Whether to automatically submit the proof after generation. Defaults to true. When false, a prompt to submit is shown to the user. | -| **`isCloseButtonVisible`** | boolean | Whether the close button is visible in the verification screen. Defaults to true. | diff --git a/content/docs/advance-options/meta.json b/content/docs/advance-options/meta.json deleted file mode 100644 index 4c5c098..0000000 --- a/content/docs/advance-options/meta.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "title": "Advanced Options", - "pages": ["attestor-auth", "verification", "overrides","verification-options","verification-status","web-sdk","js-injections"] -} \ No newline at end of file diff --git a/content/docs/advance-options/overrides.mdx b/content/docs/advance-options/overrides.mdx deleted file mode 100644 index 6c42b3b..0000000 --- a/content/docs/advance-options/overrides.mdx +++ /dev/null @@ -1,312 +0,0 @@ ---- -title: Overrides -description: Instructions on how to override the default configuration of Reclaim Protocol's InApp SDKs ---- - -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; - -# Get Started - -Many configurations in the InApp SDKs can be overridden. For example, a different attestor can be used, or we can update app info that appears in the verification flow. - - - Reclaim Protocol InApp SDK has some overrides which are restricted and require a **capability access token**. This can be made available upon request. Contact our team to discuss implementation details. - - -The `setOverrides` method allows you to customize various aspects of the Reclaim InApp SDK's behavior. This documentation covers all available override options and their usage. - -## Basic Usage - -```typescript -const reclaimVerification = new ReclaimVerification(); -reclaimVerification.setOverrides({ - // override configurations -}); -``` - -For example of how to use overrides, see: -- [The React Native example's App.overrides.tsx](https://github.com/reclaimprotocol/reclaim-inapp-reactnative-sdk/blob/main/samples/example_new_arch/src/App.overrides.tsx). -- [The Capacitor example's overrides.ts](https://github.com/reclaimprotocol/reclaim-inapp-capacitor-sdk/tree/main/example-app/src.overrides) - -## Available Override Options - -### Provider Configuration - -Configure custom provider settings: - -```typescript -provider: { - // Custom provider JSON configuration - // Useful for overriding default provider settings or testing with custom providers - jsonString: await fetchProviderConfig() -} -``` - -or - -```typescript -provider: { - // Custom provider JSON configuration - // A url to a json file that contains the provider configuration - url: 'https://api.example.org/some-api/providers/6d3f6753-7ee6-49ee-a545-62f1b1822ae5' -} -``` - -- The JSON string or url must point to a valid provider configuration that follows the [provider schema](#provider-schema). - -#### Provider Schema - -The Schema of Reclaim HTTP Provider used by Reclaim Protocol's InApp SDKs - - - -```prisma -model HttpProvider { - id String @id - httpProviderId String @unique - name String - logoUrl String - # The url that the user will be redirected to when verification starts. - url String - urlType urlType? - method RequestMethodType @default(GET) - body String? - # The url that is likely the login url address of the website used by the provider. - loginUrl String - customInjection String? - bodySniff BodySniff? - userAgent UserAgentSettings? - geoLocation String? - matchType String? @default("greedy") - injectionType InjectionType @default(MSWJS) - disableRequestReplay Boolean @default(false) - providerHash String? - additionalClientOptions AdditionalClientOptions? - verificationType VerificationType? @default(WITNESS) - expectedPageUrl String? - pageTitle String? - requestData RequestData[] -} - -type AdditionalClientOptions { - supportedProtocolVersions TLSVersion[] -} - -enum TLSVersion { - TLS1_2 - TLS1_3 -} - -enum InjectionType { - MSWJS - NONE -} - -type BodySniff { - enabled Boolean? - regex String? - template String? -} - -type UserAgentSettings { - ios String? - android String? -} - -enum urlType { - REGEX - CONSTANT - TEMPLATE -} - -type RequestData { - url String - expectedPageUrl String? - urlType urlType - method RequestMethodType - responseMatches ResponseMatch[] - responseRedactions ResponseRedaction[] - bodySniff BodySniff? - # A unique hash of the request data - requestHash String -} - -enum RequestMethodType { - GET - POST -} - -type ResponseMatch { - value String - type String - invert Boolean @default(false) - description String? -} - -type ResponseRedaction { - xPath String? - jsonPath String? - regex String? - hash String? -} -``` - - - - -Examples of provider schema can be found as provider configurations in the `https://api.reclaimprotocol.org/api/providers/${provider_id}` http api. For example, [Devtool's Http Api for Github Username Provider](https://api.reclaimprotocol.org/api/providers/6d3f6753-7ee6-49ee-a545-62f1b1822ae5). - -Note: -- These examples have a different structure where the provider configuration is nested under a 'providers' key, rather than being the root object. Therefore, the `https://api.reclaimprotocol.org/api/providers/${provider_id}` http apis cannot be used as direct parameters for provider overrides by url in this SDK. -- For use with `jsonString`, provider the value of the 'providers' key in the `jsonString` parameter. - -### Logging Configuration - -Control SDK logging behavior: - -```typescript -logConsumer: { - // Disable/enable telemetry collection - canSdkCollectTelemetry: false, - - // Disable/enable SDK console logging - canSdkPrintLogs: false, - - // Custom log handler function - onLogs: (logJsonString, _) => { - console.log(logJsonString); - } -} -``` - -### App Information - -Customize the application's identity during claim creation: - -```typescript -appInfo: { - // Custom application name - appName: "Your App Name", - - // Custom application logo/image - appImageUrl: "https://your-app-image-url.com/image.png" -} -``` - -### Feature Options - -Configure SDK behavior and features: - -```typescript -featureOptions: { - // Cookie persistence configuration - cookiePersist: null, - - // Enable/disable single reclaim request mode - singleReclaimRequest: false, - - // Idle time threshold (in seconds) for manual verification trigger (Default from reclaimprotocol.org: `2`) - idleTimeThresholdForManualVerificationTrigger: 2, - - // Session timeout (in seconds) for manual verification trigger (Default from reclaimprotocol.org: `180`) - sessionTimeoutForManualVerificationTrigger: 180, - - // Custom attestor browser RPC URL (Default from reclaimprotocol.org: `https://attestor.reclaimprotocol.org/browser-rpc`) - attestorBrowserRpcUrl: 'https://attestor.reclaimprotocol.org/browser-rpc', - - // Enable/disable response redaction regex escaping by the app (Default from reclaimprotocol.org: `false`) - isResponseRedactionRegexEscapingEnabled: false, - // Whether AI Flow can be enabled by the SDK. (Default from reclaimprotocol.org: `false`) - isAIFlowEnabled: false, -} -``` - -Setting all values to non-null values will prevent the SDK from fetching feature settings from reclaim protocol APIs server. - -### Session Management -Handle session-related events: -```typescript -sessionManagement: { - // Session logging handler - onLog: (event) => { - console.log(event); - }, - - // Session creation request handler - // Return true to allow session creation - // Returning false will cancel the session with session expired exception. - onSessionCreateRequest: async (event) => { - console.log(event); - return true; - }, - - // Session update request handler - // Return true to allow session update - // Returning false will cancel the session with session expired exception. - onSessionUpdateRequest: async (event) => { - console.log(event); - return true; - } -} -``` - -## Complete Example - -Here's a full example showing all available override options: - -```typescript -reclaimVerification.setOverrides({ - provider: { - jsonString: await fetchProviderConfig() - }, - logConsumer: { - canSdkCollectTelemetry: false, - canSdkPrintLogs: false, - onLogs: (logJsonString, _) => { - console.log({ "reclaim.logs": logJsonString }); - } - }, - appInfo: { - appName: "Custom App Name", - appImageUrl: "https://placehold.co/400x400/png" - }, - featureOptions: { - cookiePersist: null, - singleReclaimRequest: false, - idleTimeThresholdForManualVerificationTrigger: 2, - sessionTimeoutForManualVerificationTrigger: 180, - attestorBrowserRpcUrl: 'https://attestor.reclaimprotocol.org/browser-rpc', - isResponseRedactionRegexEscapingEnabled: false, - isAIFlowEnabled: false - }, - sessionManagement: { - onLog: (event) => { - console.log({ "reclaim.session.log": event }); - }, - onSessionCreateRequest: async (event) => { - console.log({ "reclaim.session.createRequest": event }); - return true; - }, - onSessionUpdateRequest: async (event) => { - console.log({ "reclaim.session.updateRequest": event }); - return true; - } - } -}); -``` - -## Best Practices - -1. Set overrides before calling `startVerification` -2. Consider setting overrides only once. -3. Handle all session management events appropriately. -4. Use appropriate timeout values for your use case -5. Test thoroughly when modifying default behaviors - -## Notes - -- All override options are optional -- Overrides persist until explicitly changed or cleared with `clearAllOverrides` -- Some features may require specific override combinations to work properly -- Overriding all options will cause the app to not use *any* reclaim protocol APIs. diff --git a/content/docs/advance-options/verification-options.mdx b/content/docs/advance-options/verification-options.mdx deleted file mode 100644 index 82f06cf..0000000 --- a/content/docs/advance-options/verification-options.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Verification Options -description: Customize the default verification flow with Reclaim Protocol's InApp SDKs ---- - -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; -import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; - -## Options API - -| Prop | Type | Description | -| ---------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------- | -| **`canDeleteCookiesBeforeVerificationStarts`** | boolean | This is enabled by default. Set false to persist sessions storage for the user. (This will be replaced with `canClearWebStorage` in an upcoming update) | -| **`canUseAttestorAuthenticationRequest`** | boolean | Enable the use of authentication request when starting a verification | -| **`claimCreationType`** | 'standalone' \| 'meChain' | The type of claim creation to use. Defaults to 'standalone'. | -| **`canAutoSubmit`** | boolean | Whether to automatically submit the proof after generation. Defaults to true. When false, a prompt to submit is shown to the user. | -| **`isCloseButtonVisible`** | boolean | Whether the close button is visible in the verification screen. Defaults to true. | diff --git a/content/docs/advance-options/verification.mdx b/content/docs/advance-options/verification.mdx deleted file mode 100644 index 5882649..0000000 --- a/content/docs/advance-options/verification.mdx +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Backend Verification -description: Learn how to create session and verify with Reclaim Backend SDKs ---- - -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; - -As best practice, we **strongly** recommend verifying proofs generated from client-side SDKs with a [Reclaim Protocol Backend SDK](http://localhost:3000/backend/installation). - -## Step-by-Step Guide - -### 1. Install the SDK - -Make sure you have installed the SDKs by following the instructions on the [Installation page](./../backend/installation). - -### 2. Prepare your variables -- You will need to have the `APPLICATION_ID` and `APPLICATION_SECRET` from dev.reclaimprotocol.org. -- You will also need to add providers to your application, keep the `PROVIDER_ID` handy too. -- The providers you add to the application, will be the providers you will be able to ask the user to generate a proof for. -- Make sure you add to your [Application from the dev tool](https://dev.reclaimprotocol.org/my-applications/). - -### 3. Get request URL from Backend SDK - -- Set the `useAppClip` option to `true` when initializing proof request: `ReclaimProofRequest.init`. -- Get the `request_url` by calling `getRequestUrl` method on proof request object. - -```js -import { ReclaimProofRequest } from '@reclaimprotocol/js-sdk'; - -app.get('/reclaim/request', async (req: any, res: any) => { - try { - const reclaimProofRequest = await ReclaimProofRequest.init(APPLICATION_ID, APPLICATION_SECRET, PROVIDER_ID, { useAppClip: true }) - - const request_url = await reclaimProofRequest.getRequestUrl() - - return res.json({ request_url }) - } catch (error) { - console.error('Error generating request config:', error) - return res.status(500).json({ error: 'Failed to generate request config' }) - } -}); -``` - -### 4. Generate proof on client mobile - -- Your native mobile application should use the `request_url` from the backend and start verification with this url. - - - - -Start verification with `request_url` using the following sample code: - -```swift -let result = try await ReclaimVerification.startVerification(.url(requestUrl)) -``` - -Send `result.proofs` to the backend for verification and further processing - - - - -Start verification with `request_url` using the following sample code: - -```kotlin -ReclaimVerification.startVerificationFromUrl( - context = context, - requestUrl = requestUrl, - handler = object : ReclaimVerification.ResultHandler { - override fun onException(exception: ReclaimVerification.ReclaimVerificationException) { - // - } - - override fun onResponse(response: ReclaimVerification.Response) { - Log.d("MainActivity", response.toString()) - // response.proofs - } - } -) -``` - -Send the `response.proofs`, that was received in handler's `onResponse` method, to the backend for verification and further processing - - - - -Start verification with `request_url` using the following sample code: - -```js -const sdk = new ReclaimVerification(); -// `startVerificationFromUrl` will be added to sdk in an upcoming update. -// For now, access it from `sdk.platform`. -const result = await sdk.platform.startVerificationFromUrl(requestUrl); -``` - -Send `result.proofs` to the backend for verification and further processing - - - - -### 5. Verify proofs at backend - -- Mobile application (client) should send the proof to your backend for verification and then processing. -- Use `verifyProof` from the reclaim backend sdk for verifying the proof received from the client. - -```js -import { verifyProof } from '@reclaimprotocol/js-sdk'; - -app.post('/reclaim/verify', async (req: any, res: any) => { - try { - const data = req.body; // json object/array as body - const is_valid = await verifyProof(data); - - if (is_valid) { - return res.json({ is_valid: is_valid }) - } - return res.status(400).json({ is_valid: is_valid }) - } catch (error) { - console.error('Error verifying proof:', error) - return res.status(500).json({ error: 'Failed to verify proof' }) - } -}) -``` diff --git a/content/docs/advance-options/web-sdk.mdx b/content/docs/advance-options/web-sdk.mdx deleted file mode 100644 index deae426..0000000 --- a/content/docs/advance-options/web-sdk.mdx +++ /dev/null @@ -1,768 +0,0 @@ ---- -title: Web SDK -description: This guide provides advanced options for the Reclaim Protocol SDK across multiple platforms. These options allow you to customize and enhance your integration for specific use cases. ---- -import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; - -## Advanced Options -Reclaim SDKs provide a lot of flexibility to customize the verification process. - -### init() - -The `init` method allows you to pass additional options to customize the SDK's behavior. - - - - ```javascript - const proofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID', - // optional fields - { - useAppClip: true, // default: true - log: true, // default: false - useBrowserExtension: true, // default: true - extensionID: 'custom-extension-id', // default: 'reclaim-extension' - providerVersion: '1.0.0' - } - ) - ``` - - `useAppClip` (Default: `true`): This option enables the use of AppClip/Instant App for mobile users. Only should be set to `true` when building mobile apps. - - `log` (Default: `false`): When set to `true`, enables detailed logging for debugging purposes. - - `useBrowserExtension` (Default: `true`): This option enables the use of reclaim browser extension for desktop users. When extension is not installed, the SDK will fallback to QR code flow. - - `extensionID` (Default: `reclaim-extension`): Unique extension identifier if using a custom reclaim browser extension. - - `providerVersion`: Version of the data provider. This is needed if you are using a specific version of the data provider. - - - ```python - from reclaim_python_sdk.proof_request import ReclaimProofRequest - - proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID', - # optional fields - options={'log': True, 'provider_version': '1.0.0'} # default: False - ) - ``` - - `log`: When set to `true`, enables detailed logging for debugging purposes. - - `provider_version`: Version of the data provider. This is needed if you are using a specific version of the data provider. - - - -### Provider Versioning (optional) - -The Reclaim SDK supports semantic versioning for all providers, allowing you to optionally lock to specific versions and avoid unexpected schema changes during integration. Specifying a provider version is optionalβ€”if you do not provide one, the SDK will use the latest available version by default. - -#### Key Features - -- **Semantic Versioning**: All providers follow `MAJOR.MINOR.PATCH` format (e.g., `1.0.0`). -- **Automated Versioning**: Provider changes automatically bump the version based on impact. - -#### Version Matching in SDK - -The SDK supports flexible version targeting: - -- **Exact version**: `'1.0.0'` -- **Range operators**: `'>=1.0.0'`, `<2.0.0'`, etc. -- **Tilde (~) range**: `'~1.2.0'` resolves to the latest patch version in the `1.2.x` range. - -#### Example - - - - - ```javascript - const proofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID', - { - providerVersion: '1.0.0' // locks to specific schema version - } - ) - ``` - - - ```python - from reclaim_python_sdk.proof_request import ReclaimProofRequest - - proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID', - # optional fields - options={'provider_version': '1.0.0'} # locks to specific schema version - ) - ``` - - - -### setAppCallbackUrl() - -The `setAppCallbackUrl` method allows you to specify a custom API endpoint where verification credentials(proofs) will be sent upon successful generation. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setAppCallbackUrl('https://your-api.com/receive-proofs') // your custom callback url here - - ``` - - Parameters for `setAppCallbackUrl`: - - `URL`: The URL of the API endpoint where proofs will be sent. - - `jsonProofResponse` (Optional) (Default: `false`): When set to `false`, the proof is returned as a url encoded message in the response. When set to `true`, the proof is returned as a JSON object in the response. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setAppCallbackUrl('https://your-api.com/receive-proofs') // your custom callback url here - - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ); - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setAppCallbackUrl('https://your-api.com/receive-proofs') // your custom callback url here - - ``` - - - ```python - from reclaim_python_sdk.proof_request import ReclaimProofRequest - - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - # Make sure to set this before starting the verification session. - reclaim_proof_request.set_app_callback_url('https://your-api.com/receive-proofs') # your custom callback url here - - ``` - - - -This is the recommended way to receive proofs directly on your endpoint. Make sure to use proper middleware to parse the proof object in the response. Eg. `express.text({ type: '*/*', limit: '50mb' })` in express.js. - -### setRedirectUrl() - -The `setRedirectUrl` method allows you to specify a custom URL where users will be redirected after the successful verification process. - - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setRedirectUrl('https://your-app.com/verification-complete') - - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ); - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setRedirectUrl('https://your-app.com/verification-complete'); // you can add a deep link to your app here - - ``` - - - Setting Up Deep Linking in Your Flutter App - - Follow these steps to implement deep linking functionality: - - 1. Configure Custom URL Scheme - - Define a unique URL scheme for your app (example: 'yourapp://') - - This allows your app to respond when users click links with your custom scheme - - 2. Implement Route Handler - - Create a dedicated route to handle the '/verification-complete' path - - This route will be triggered when users access your app through deep links - - 3. Handle Deep Link Data - - Extract and process any parameters or data passed through the deep link - - Use this data to navigate users to the appropriate screen or perform specific actions - - For detailed implementation instructions and best practices, refer to the official Flutter documentation: - [Deep Linking in Flutter](https://docs.flutter.dev/ui/navigation/deep-linking) - - - - - ```python - from reclaim_python_sdk.proof_request import ReclaimProofRequest - - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - # Make sure to set this before starting the verification session. - reclaim_proof_request.set_redirect_url('https://your-app.com/verification-complete') - - ``` - - - -### Exporting and Importing SDK Configuration - -The SDK provides methods to export and import the entire configuration as a JSON string. This allows you to use the same verification session across different platforms with all our SDKs. - - - - ```javascript - // Export configuration - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - const reclaimProofRequestConfig = reclaimProofRequest.toJsonString() - - - // On a different service or application import the configuration - const reclaimProofRequest = await ReclaimProofRequest.fromJsonString(reclaimProofRequestConfig) - - // Start the verification session using either `getRequestUrl` or `triggerReclaimFlow` - - ``` - - - ```dart - // Export configuration - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ); - - final reclaimProofRequestConfig = reclaimProofRequest.toJsonString(); - - // On a different service or application import the configuration - final reclaimProofRequest = await ReclaimProofRequest.fromJsonString(reclaimProofRequestConfig); - final requestUrl = await reclaimProofRequest.getRequestUrl(); - ``` - - - ```python - # Export configuration - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - reclaim_proof_request_config = reclaim_proof_request.to_json_string() - - # On a different service or application import the configuration - reclaim_proof_request = await ReclaimProofRequest.from_json_string(reclaim_proof_request_config) - request_url = await reclaim_proof_request.get_request_url() - ``` - - - -### verifyProof() - -The SDK provides a method to verify the verification credentials(proofs) to ensure their authenticity. This is particularly useful when receiving proofs in your backend. - - - - ```javascript - import { verifyProof } from '@reclaimprotocol/js-sdk' - - // make sure proofObject is of type 'Proof' Object - const isValid = await verifyProof(proofObject) - if (isValid) { - console.log('Proof is valid!') - } else { - console.log('Invalid proof - signature verification failed') - } - ``` - - - ```dart - import 'package:reclaim_sdk/reclaim.dart'; - - // make sure proofObject is of type 'Proof' Object - final isValid = await verifyProof(proofObject); - if (isValid) { - print('Proof is valid!'); - } else { - print('Invalid proof - signature verification failed'); - } - ``` - - - ```python - from reclaim_python_sdk import verify_proof, Proof - - # make sure proof_object is of type 'Proof' Object - proof_object = Proof.from_json(proof_json_object) - is_valid = await verify_proof(proof_object) - if is_valid: - print('Proof is valid!') - else: - print('Invalid proof - signature verification failed') - ``` - - - - - The reclaim-rust-sdk crate is currently in development and only supports verify proof for now. - - - Install the reclaim-rust-sdk crate in your project. - - ```bash - cargo add reclaim-rust-sdk@=0.1.0 - cargo add serde_json@=1.0.0 - ``` - - Add the following to your `Cargo.toml` file: - - ```toml - [dependencies] - reclaim-rust-sdk = "0.1.0" - serde_json = "1.0.0" - ``` - - ```rust - use reclaim_rust_sdk::verify_proof; - use serde_json::json; - - let proof: reclaim_rust_sdk::Proof = serde_json::from_value(proof_json).unwrap(); - - let is_valid = verify_proof(&proof); - if is_valid { - println!("βœ… Proof is valid!"); - } else { - println!("❌ Invalid proof - signature verification failed"); - } - ``` - - - - -### addContext() - -Use the `addContext` method to include any additional information in your verification credentials(proofs). This information will be included in the proof object under the `context` field. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Make sure to set this before starting the verification session. - reclaimProofRequest.addContext('0x1234567890abcdef', 'User registration proof') - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ); - - // Make sure to set this before starting the verification session. - reclaimProofRequest.addContext('0x1234567890abcdef', 'User registration proof'); - - ``` - - - ```python - from reclaim_python_sdk import ReclaimProofRequest - - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - # Make sure to set this before starting the verification session. - reclaim_proof_request.add_context('0x1234567890abcdef', 'User registration proof') - - ``` - - - -- `contextId`: Unique hex address identifier (string) -- `Context message`: Additional information to be included in the proof object (string) - - -The contextId must be a valid hex address (starting with '0x' and containing only 0-9 and a-f). - - -### setParams() - -The `setParams` method lets you define specific conditions for proof generation, enabling selective triggering for verification sessions. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setParams({ - minConnections: '500', - industry: 'Technology' - }) - - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ); - - // Make sure to set this before starting the verification session. - reclaimProofRequest.setParams({ - 'minConnections': '500', - 'industry': 'Technology' - }); - - ``` - - - ```python - from reclaim_python_sdk import ReclaimProofRequest - - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - # Make sure to set this before starting the verification session. - reclaim_proof_request.set_params({ - 'minConnections': '500', - 'industry': 'Technology' - }) - - ``` - - - - - Proof generation will fail if the specified parameters are not present on the provider website. - - -### isBrowserExtensionAvailable() - -The `isBrowserExtensionAvailable` method checks if any Reclaim browser extension is installed on the user's device. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Check if browser extension is available - const isExtensionAvailable = await reclaimProofRequest.isBrowserExtensionAvailable() - - if (isExtensionAvailable) { - console.log('Reclaim browser extension is installed') - // Extension will be used automatically with triggerReclaimFlow() - } else { - console.log('Browser extension not available, will use QR code flow') - } - ``` - - - -### setModalOptions() - -You can use `setModalOptions` method to customize the modal appearance and behavior of the QR code modal popup (appears on desktop when browser extension is not installed). -This is applicable only when using `triggerReclaimFlow` method. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - // Customize modal appearance before triggering flow - reclaimProofRequest.setModalOptions({ - title: 'Verify Your Account', - description: 'Scan the QR code with your mobile device or install our browser extension', - darkTheme: false, // Enable dark theme (default: false) - extensionUrl: 'https://chrome.google.com/webstore/detail/reclaim', // Your extension download url - showExtensionInstallButton: true, // Show extension install button (default: true) - modalPopupTimer: 1, // Modal popup timer in minutes (default: 1) - onClose: () => { - console.log('Modal closed') - } // Callback function to be called when modal is closed - }) - - // Trigger the verification flow with custom modal - await reclaimProofRequest.triggerReclaimFlow() - ``` - - - -**Modal Options:** -Note: All the options are optional and can be used individually. -- `title`: Custom title for the modal dialog -- `description`: Custom description text shown to users -- `darkTheme` (Default: `false`): Boolean to enable dark theme styling -- `extensionUrl`: Custom URL to install/download the browser extension -- `showExtensionInstallButton` (Default: `false`): Show extension install button -- `modalPopupTimer` (Default: `1`): Modal popup timer in minutes -- `onClose` (Default: `undefined`): Callback function that can be called when modal is closed for custom logic - -### closeModal() - -You can use `closeModal` method to manually close the modal popup. This is applicable only when using `triggerReclaimFlow` method. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - - // Trigger the verification flow with custom modal - await reclaimProofRequest.triggerReclaimFlow() - - // Close the modal popup - reclaimProofRequest.closeModal() - ``` - - - -## Options to get various Session Details - -The SDK provides methods to fetch additional details about the verification session. - -### getRequestUrl() - -The `getRequestUrl` method returns the URL to start the verification session. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - const requestUrl = await reclaimProofRequest.getRequestUrl() - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - final requestUrl = await reclaimProofRequest.getRequestUrl() - ``` - - - ```python - from reclaim_python_sdk import ReclaimProofRequest - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - request_url = await reclaim_proof_request.get_request_url() - ``` - - - - - -### getSessionId() - -The `getSessionId` method returns the unique identifier for the verification session. - - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - const sessionId = await reclaimProofRequest.getSessionId() - ``` - - - -### getStatusUrl() - -The `getStatusUrl` method returns the URL to check the status of the verification session. You can use this URL to poll the status of the verification session. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - const statusUrl = await reclaimProofRequest.getStatusUrl() - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - final statusUrl = await reclaimProofRequest.getStatusUrl() - ``` - - - ```python - from reclaim_python_sdk import ReclaimProofRequest - - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - status_url = await reclaim_proof_request.get_status_url() - ``` - - - -### getAppCallbackUrl() - -The `getAppCallbackUrl` method returns the URL where the verification credentials(proofs) will be sent upon successful generation. - - - - ```javascript - const reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - const appCallbackUrl = await reclaimProofRequest.getAppCallbackUrl() - ``` - - - ```dart - final reclaimProofRequest = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - - final appCallbackUrl = await reclaimProofRequest.getAppCallbackUrl() - ``` - - - ```python - from reclaim_python_sdk import ReclaimProofRequest - reclaim_proof_request = await ReclaimProofRequest.init( - 'YOUR_RECLAIM_APP_ID', - 'YOUR_RECLAIM_APP_SECRET', - 'YOUR_PROVIDER_ID' - ) - app_callback_url = await reclaim_proof_request.get_app_callback_url() - ``` - - - - - - - -## Understanding the Proof Structure - -When using any Reclaim SDK (JavaScript, React Native, Flutter), a proof is generated and returned upon successful verification. This proof contains several key components that provide detailed information about the verification process. Below is a generic structure of a proof: - -```json -{ - "identifier": "unique_identifier_for_proof", // string - "claimData": { - "provider": "provider_type", // string - "parameters": "verified_data_from_website", // stringified JSON object - "owner": "owner_address", // string - "timestampS": "timestamp_of_proof_generation", // int - "context": "additional_context_information", // stringified JSON object - "epoch": "epoch_number" // int - }, - "signatures": [ - "signature_of_proof" // string - ], - "witnesses": [ - { - "id": "witness_id", // string - "url": "witness_url" // string - } - ], - // publicData is optional and only available if provider supports it else it will be empty - "publicData": {} // stringified JSON object -} -``` - diff --git a/content/docs/ai-agent/index.mdx b/content/docs/ai-agent/index.mdx deleted file mode 100644 index 3728132..0000000 --- a/content/docs/ai-agent/index.mdx +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: AI Agent -description: The A2A protocol compatible Verification AI Agent ---- - -## Verification AI Agent - -