### Start Development Server Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Start the Vite development server to run the React application. ```sh npm run dev ``` -------------------------------- ### Start Development Server Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/01-project-overview.md Command to start the development server with hot module replacement enabled. ```bash npm run dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Install all necessary project dependencies using npm. ```sh npm install ``` -------------------------------- ### Install Dependencies Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/01-project-overview.md Command to install all project dependencies using npm. ```bash npm install ``` -------------------------------- ### Typical ALTCHA Development Setup Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md This setup is optimized for development and testing. It enables test mode, activates debug output, and uses a minimal configuration for rapid iteration. The 'test' flag allows operation without a server. ```typescript { // Test mode - no server required test: true, // Debug output debug: true, // Layout for testing display: 'standard', type: 'native', // Minimal config minDuration: 100, } ``` -------------------------------- ### Install ALTCHA Package Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Install the ALTCHA package using npm. This is the first step to integrate ALTCHA into your project. ```bash npm install altcha --save ``` -------------------------------- ### New Style Definition Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Example of creating a CSS file for a new component. ```css .my-component { color: blue; } ``` -------------------------------- ### Verify Altcha Type Definitions Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md After installation, check the `node_modules/altcha/dist/types/` directory to confirm that the type definition files are present. ```bash # If still missing, check node_modules ls node_modules/altcha/dist/types/ ``` -------------------------------- ### Install ALTCHA Widget Package Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Install the ALTCHA widget package as a dependency for your React project. ```sh npm install altcha --save ``` -------------------------------- ### Initiate Verification with verify() Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Basic usage of the `verify()` method to start the proof-of-work calculation. Check the result for successful verification or cancellation. ```typescript const result = await widget.verify() if (result) { console.log('Verified:', result.payload) } else { console.log('Verification failed or cancelled') } ``` -------------------------------- ### Install Altcha Package Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md If TypeScript cannot find modules like 'altcha/types', ensure the 'altcha' package is installed in your project using npm. ```bash # Make sure altcha is installed npm install altcha ``` -------------------------------- ### Complete ALTCHA Configuration Example Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md This snippet shows a comprehensive set of configuration options for ALTCHA, including challenge and verification URLs, display preferences, branding, localization, interaction settings, form integration, performance tuning, and debugging. Use this as a reference for all available settings. ```typescript const configuration: Partial = { // Challenge and verification challenge: 'https://api.example.com/challenge', verifyUrl: 'https://api.example.com/verify', serverVerificationFields: true, serverVerificationTimeZone: true, // Display display: 'floating', type: 'switch', floatingAnchor: '#submit-button', floatingOffset: 16, floatingPlacement: 'bottom', floatingPersist: 'focus', // Branding hideFooter: false, hideLogo: false, // Localization language: 'en', // Interaction auto: 'onsubmit', minDuration: 500, timeout: 90000, // Form name: 'altcha_payload', validationMessage: 'Please complete the verification', // Performance workers: 4, humanInteractionSignature: true, // Debugging (remove in production) debug: false, } export const configurationString = JSON.stringify(configuration) ``` -------------------------------- ### Create New Vite Project Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Create a new Vite project with the React and TypeScript template. Use this command to start a new project from scratch. ```sh npm create vite@latest my-react-app -- --template react-ts ``` -------------------------------- ### Migrate from Widget to Altcha Component Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/09-react-hooks-and-patterns.md This example shows the migration from directly querying the DOM for a widget to using the Altcha React component with refs. The component provides a cleaner API and type-safe ref access. ```typescript function MyForm() { const altchaRef = useRef<{ value: string | null }>(null) const handleSubmit = () => { const payload = altchaRef.current?.value // payload directly accessible } } ``` -------------------------------- ### New Component Definition Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Example of creating a new React component with TypeScript, including props and default export. ```typescript interface MyComponentProps { prop1: string } export const MyComponent = ({ prop1 }: MyComponentProps) => { return
{prop1}
} export default MyComponent ``` -------------------------------- ### Typical ALTCHA Production Setup Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md This configuration is suitable for a production environment, focusing on essential endpoints, standard layout, security, and user experience. Debugging and testing flags are disabled. ```typescript { // Required endpoints challenge: 'https://api.example.com/challenge', verifyUrl: 'https://api.example.com/verify', // Layout display: 'standard', type: 'checkbox', // Security credentials: 'same-origin', serverVerificationFields: false, // UX minDuration: 500, language: 'en', // Debugging disabled debug: false, test: false, mockError: false, } ``` -------------------------------- ### show() Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Makes the Altcha widget visible on the page. This is typically used to display the widget when it's needed, for example, after a user interaction. ```APIDOC ## show() ### Description Shows the widget, making it visible on the page. ### Signature ```typescript show(): void ``` ### Parameters None. ### Return Type `void` ### Usage Examples **Show widget when needed:** ```typescript widget.show() ``` **Show after form interaction:** ```typescript form.addEventListener('focus', () => { widget.show() }) ``` ``` -------------------------------- ### Module Resolution: npm Package Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Explains the order Vite checks when importing a module by name, starting with node_modules. ```javascript import X from 'name' ``` -------------------------------- ### Track Verification Progress with Statechange Event Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/07-events-and-listeners.md Listen for the 'statechange' event on the Altcha widget to track its verification status. This example logs the current state and payload when verified. ```typescript widget.addEventListener('statechange', (event) => { const detail = (event as CustomEvent).detail switch (detail.state) { case 'unverified': console.log('🔲 Not verified') break case 'verifying': console.log('⟳ Verifying...') break case 'verified': console.log('✓ Verified') console.log('Payload:', detail.payload) break case 'error': console.error('✗ Error:', detail.error) break case 'expired': console.log('⏱ Expired') break } }) ``` -------------------------------- ### Get All Current Widget Settings Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Retrieve the entire current configuration object of the ALTCHA widget using `getConfiguration()`. The configuration can then be logged or processed as needed. ```typescript const config = widget.getConfiguration() console.log('Current configuration:', JSON.stringify(config, null, 2)) ``` -------------------------------- ### Complete ALTCHA Widget Method Usage in React Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md This example shows how to use various ALTCHA widget methods like getState, reset, verify, hide, setState, configure, and updateUI within a React functional component. It covers handling verification logic, updating widget configuration, and integrating with form submission. ```typescript import { useRef } from 'react' function AdvancedForm() { const widgetRef = useRef(null) const formRef = useRef(null) const handleVerify = async () => { const widget = widgetRef.current if (!widget) return // Check current state const currentState = widget.getState() console.log('Current state:', currentState) // If already verified, reset if (currentState === 'verified') { widget.reset() } // Start verification with custom options try { const result = await widget.verify({ concurrency: 4, minDuration: 1000, }) if (result) { console.log('Verified! Payload:', result.payload) widget.hide() } else { widget.setState('error', 'Verification cancelled') } } catch (error) { widget.setState('error', 'Verification error: ' + error.message) } } const handleConfigChange = async () => { const widget = widgetRef.current if (!widget) return // Update configuration await widget.configure({ debug: true, language: 'en', minDuration: 500, }) // Refresh UI widget.updateUI() // Log new config const config = widget.getConfiguration() console.log('Updated config:', config) } const handleFormSubmit = async (e: React.FormEvent) => { e.preventDefault() const widget = widgetRef.current if (!widget) return // Auto-verify if not done if (widget.getState() !== 'verified') { const result = await widget.verify() if (!result) { widget.setState('error', 'Verification required') return } } // Submit form console.log('Submitting form...') // Send to server } return (
) } ``` -------------------------------- ### Cypress E2E Test for ALTCHA Widget Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Example of an end-to-end test using Cypress to verify the ALTCHA widget's existence and state changes. ```typescript // Cypress example cy.get('altcha-widget') .should('exist') .then($widget => { // Widget should emit statechange with verified state cy.get('altcha-widget').should('have.attr', 'data-state', 'verified') }) ``` -------------------------------- ### Verify ALTCHA Token in Python/Flask Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md This example demonstrates verifying an ALTCHA token by sending a POST request to the ALTCHA verification endpoint using the `requests` library. Ensure the `ALTCHA_HMAC_SECRET` environment variable is set. ```python from flask import Flask, request, jsonify import json import requests import os app = Flask(__name__) ALTCHA_VERIFY_URL = 'https://api.altcha.org/verify' @app.route('/api/contact', methods=['POST']) def contact(): payload = request.form.get('_altcha') if not payload: return jsonify({'error': 'ALTCHA token required'}), 400 try: # Verify with ALTCHA verification endpoint response = requests.post(ALTCHA_VERIFY_URL, json={ 'payload': payload, 'hmacSecret': os.getenv('ALTCHA_HMAC_SECRET'), }) result = response.json() if not result.get('verified'): return jsonify({'error': 'Verification failed'}), 400 # Process verified request name = request.form.get('name') message = request.form.get('message') # Save to database, send email, etc. return jsonify({'success': True}) except Exception as e: return jsonify({'error': 'Verification error'}), 500 ``` -------------------------------- ### Import Dependencies for App Component Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/03-app-component.md Imports React hooks, logo assets, the ALTCHA component, and the main CSS file. The `useRef` hook is used to get a reference to the Altcha component. ```typescript import { useRef } from 'react' import reactLogo from './assets/react.svg' import viteLogo from '/vite.svg' import Altcha from './Altcha' import './App.css' ``` -------------------------------- ### Use ALTCHA in a Form Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Integrate the `Altcha` component into your React form. This example shows how to handle form submission, including checking for ALTCHA verification and appending the payload to form data. ```typescript import { useRef } from 'react' import Altcha from './Altcha' function ContactForm() { const altchaRef = useRef<{ value: string | null }>(null) const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() const payload = altchaRef.current?.value if (!payload) { alert('Please complete ALTCHA verification') return } // Send form data with payload to your server const formData = new FormData(e.currentTarget) formData.append('_altcha', payload) const response = await fetch('/api/contact', { method: 'POST', body: formData, }) if (response.ok) { alert('Message sent!') } } return (
) } export default ContactForm ``` -------------------------------- ### Preview Production Build Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/01-project-overview.md Command to preview the production build locally. ```bash npm run preview ``` -------------------------------- ### Vite Build Output: After Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Illustrates the output directory structure after a Vite build, including bundled and optimized assets. ```bash dist/ ├── index.html # HTML with script tags ├── assets/ │ ├── index-HASH.js # Bundled JavaScript │ ├── index-HASH.css # Bundled CSS │ └── react-HASH.svg # Optimized logo └── vite.svg # Copied from public/ ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Change the current directory to the newly created project folder. ```sh cd my-react-app ``` -------------------------------- ### Vite Build Output: Before Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Shows the typical source directory structure before running the build command. ```bash src/ ├── main.tsx ├── App.tsx ├── Altcha.tsx ├── App.css ├── index.css └── assets/ └── react.svg ``` -------------------------------- ### New Type Definition Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Example of defining a new interface for type checking in TypeScript. ```typescript export interface MyType { field: string } ``` -------------------------------- ### Build for Production Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/01-project-overview.md Command to type-check and build an optimized production bundle for the application. ```bash npm run build ``` -------------------------------- ### Project Structure Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/01-project-overview.md Illustrates the directory and file organization of the ALTCHA Starter React TypeScript project. ```tree altcha-starter-react-ts/ ├── src/ │ ├── main.tsx # Application entry point │ ├── App.tsx # Root component with form │ ├── Altcha.tsx # ALTCHA widget wrapper component │ ├── App.css # Application styles │ ├── index.css # Global styles │ ├── assets/ # Static assets (React logo) │ └── vite-env.d.ts # Vite environment type definitions ├── public/ # Public static assets ├── index.html # HTML template ├── package.json # Dependencies and scripts ├── tsconfig.json # TypeScript configuration ├── tsconfig.app.json # App-specific TypeScript settings ├── tsconfig.node.json # Build-specific TypeScript settings ├── vite.config.ts # Vite configuration └── .eslintrc.cjs # ESLint configuration ``` -------------------------------- ### HTML Entry Point Structure Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md The main HTML file serves as the entry point for the browser, containing the root div for React and loading the main application script as an ES module. It is designed for modern browsers. ```html
``` -------------------------------- ### Clone ALTCHA Starter Repository Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Clone the official ALTCHA starter repository for a Vite + React project. Navigate into the cloned directory. ```sh git clone https://github.com/altcha-org/altcha-starter-react-ts.git cd altcha-starter-react-ts ``` -------------------------------- ### Custom Verification Function Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Integrate a custom verification logic by providing a `verifyFunction` that handles the verification process, for example, by calling a custom API endpoint. ```typescript { verifyFunction: async (payload) => { // Custom verification logic const response = await fetch('/api/verify-altcha', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ payload }), }) return response.json() } } ``` -------------------------------- ### Get Widget State Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Retrieves the current verification state of the widget. Use this to conditionally enable or disable form elements based on verification status. ```typescript const state = widget.getState() if (state === 'verified') { console.log('Widget is verified') // Enable submit button submitBtn.disabled = false } else { submitBtn.disabled = true } ``` ```typescript const state = widget.getState() switch (state) { case 'verified': console.log('✓ Verified') break case 'verifying': console.log('⟳ Verifying...') break case 'error': console.log('✗ Error') break case 'expired': console.log('⏱ Expired') break default: console.log('? Not verified') } ``` -------------------------------- ### Configuration Options Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/00-index.md Key configuration options for the ALTCHA widget. ```APIDOC ## Configuration Options ### Description Key options to configure the ALTCHA widget's behavior and appearance. | Option | Type | Default | Purpose | |---|---|---|---| | `challenge` | `Challenge | string | null` | `null` | Challenge data or URL | | `verifyUrl` | `string | null` | `null` | Server verification endpoint | | `display` | `'standard' | 'bar' | ...` | `'standard'` | Widget display mode | | `test` | `boolean` | `false` | Test mode (mocks verification) | | `debug` | `boolean` | `false` | Enable console logging | | ...and 40+ more options | — | — | See full reference | ``` -------------------------------- ### Initialize React App Entry Point Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md This is the main entry point for a React application, responsible for rendering the root component into the DOM. It uses ReactDOM.createRoot for concurrent features and React.StrictMode for development checks. ```typescript import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.tsx' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( , ) ``` -------------------------------- ### Anchor Floating Widget with HTML Element Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Anchor the floating widget to a specific HTML element. This requires obtaining a reference to the DOM element, for example, using document.getElementById. ```typescript { display: 'floating', floatingAnchor: document.getElementById('submit-btn') } ``` -------------------------------- ### Controlled Exposure Example Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/09-react-hooks-and-patterns.md Demonstrates controlled exposure of component state and methods. Parents can access the exposed 'value' but not internal widget methods or raw DOM refs. ```typescript // Parent CANNOT access: widgetRef.current // ✗ Raw DOM ref not exposed widgetRef.current.verify // ✗ Widget methods not exposed // Parent CAN access: altchaRef.current.value // ✓ Payload only ``` -------------------------------- ### Project Dependencies Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Lists the core runtime dependencies for the project, including React, ReactDOM, and the altcha library. These are essential for the application's functionality. ```json { "dependencies": { "altcha": "^3.1.0", "react": "^19.2.7", "react-dom": "^19.2.7" } } ``` -------------------------------- ### Update Multiple Widget Settings Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Demonstrates updating several configuration options simultaneously using the `configure()` method, such as debug mode, display preference, language, and minimum verification duration. ```typescript await widget.configure({ debug: false, display: 'floating', language: 'en', minDuration: 1000, }) ``` -------------------------------- ### Get Current Debug Setting Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Retrieve the current widget configuration using `getConfiguration()` and access specific settings like `debug`. This allows you to inspect the active configuration. ```typescript const config = widget.getConfiguration() console.log('Debug enabled:', config.debug) ``` -------------------------------- ### Absolute Imports for npm Packages Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Use for importing modules from installed npm packages. These are resolved from `node_modules/` and respect the `exports` field in `package.json`. Both named and default exports are supported. ```typescript import React from 'react' import ReactDOM from 'react-dom/client' import { useRef, useEffect } from 'react' ``` -------------------------------- ### getConfiguration() Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Retrieves the current configuration settings of the ALTCHA widget. ```APIDOC ## getConfiguration() ### Description Retrieves the current widget configuration. ### Signature ```typescript getConfiguration(): Configuration ``` ### Parameters None. ### Response #### Success Response - **Type**: `Configuration` Complete current configuration object. ### Usage Examples **Get current debug setting:** ```typescript const config = widget.getConfiguration() console.log('Debug enabled:', config.debug) ``` **Check current display mode:** ```typescript const config = widget.getConfiguration() if (config.display === 'floating') { console.log('Widget is in floating mode') } ``` **Get all current settings:** ```typescript const config = widget.getConfiguration() console.log('Current configuration:', JSON.stringify(config, null, 2)) ``` ``` -------------------------------- ### TypeScript Strict Mode Example Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Illustrates errors caught by strict mode: unused local variables, unused function parameters, and missing 'break' statements in switch cases. ```typescript // ✗ Error: var1 is declared but not used const var1 = 'unused' // ✗ Error: unused parameter const handler = (unused: string) => { } // ✗ Error: missing break switch (x) { case 1: console.log('1') // falls through case 2: console.log('2') } ``` -------------------------------- ### verify() Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Initiates the proof-of-work calculation for verification. It can accept options to control concurrency, cancellation, and minimum duration. ```APIDOC ## verify() ### Description Initiates verification (proof-of-work calculation). ### Signature ```typescript verify(options?: VerifyOptions): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `options` (`VerifyOptions`) - **Type**: `VerifyOptions` - **Required**: No - **Description**: Verification options object **VerifyOptions Interface:** ```typescript interface VerifyOptions { concurrency?: number controller?: AbortController minDuration?: number } ``` | Field | Type | Default | Description | |---|---|---|---| | `concurrency` | `number` | Config value | Number of parallel workers | | `controller` | `AbortController` | — | Abort controller to cancel verification | | `minDuration` | `number` | Config value | Minimum verification time (ms) | ### Response #### Success Response - **Type**: `Promise` **VerifyResult Interface:** ```typescript interface VerifyResult { challenge?: Challenge payload: string solution?: Solution } ``` | Field | Type | Description | |---|---|---| | `challenge` | `Challenge` | Original challenge object | | `payload` | `string` | Serialized verification payload (JSON) | | `solution` | `Solution` | Proof-of-work solution data | Returns `null` if verification was cancelled or failed. #### Throws - Rejects on network error (when fetching challenge) - Rejects on timeout - Rejects on worker errors ### Usage Examples **Basic verification:** ```typescript const result = await widget.verify() if (result) { console.log('Verified:', result.payload) } else { console.log('Verification failed or cancelled') } ``` **With concurrency control:** ```typescript const result = await widget.verify({ concurrency: 2, // Use only 2 workers }) ``` **With timeout control:** ```typescript const controller = new AbortController() const timeoutId = setTimeout(() => controller.abort(), 5000) try { const result = await widget.verify({ controller }) console.log('Verified:', result.payload) } catch (error) { console.error('Verification timed out or cancelled:', error) } finally { clearTimeout(timeoutId) } ``` **With custom minimum duration:** ```typescript const result = await widget.verify({ minDuration: 2000 // Wait at least 2 seconds }) ``` ``` -------------------------------- ### Configure Fetch Credentials Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Use the 'credentials' option to define how credentials should be handled for challenge/verify network requests. Options include 'omit', 'same-origin', and 'include'. ```typescript { credentials: 'include' // Send cookies with requests } ``` -------------------------------- ### Run ESLint Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/01-project-overview.md Command to run ESLint with a strict configuration for code quality checks. ```bash npm run lint ``` -------------------------------- ### Development/Testing Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Use this configuration for local development and testing to mock successful verification and enable debugging. ```typescript { test: true, debug: true, mockError: false, } ``` -------------------------------- ### Configure ALTCHA Widget via Prop Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Pass configuration as a JSON string to the `` component. This is recommended for static configurations. ```typescript ``` ```typescript ``` -------------------------------- ### Build Script Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md The `build` script in `package.json` combines TypeScript compilation with Vite for building the project. ```json { "scripts": { "build": "tsc -b && vite build" } } ``` -------------------------------- ### Development Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Use this configuration for development to enable logging and test mode. This setting is located in `src/Altcha.tsx`. ```typescript { debug: true, // Development logging test: true, // Test mode (no server) } ``` -------------------------------- ### Production Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Switch to this configuration for production to disable development features and set your API endpoints. Ensure `challenge` and `verifyUrl` are correctly set to your Altcha server URLs. ```typescript { debug: false, test: false, challenge: 'https://your-api.com/challenge', verifyUrl: 'https://your-api.com/verify', language: 'en', } ``` -------------------------------- ### Widget Methods Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/00-index.md Methods available on the ALTCHA widget instance. ```APIDOC ## Widget Methods ### Description Methods available on the ALTCHA widget instance for programmatic control. ### Methods - `verify(options?: VerifyOptions): Promise`: Verifies the widget's current state. - `configure(config: Partial): Promise`: Updates the widget's configuration. - `getConfiguration(): Configuration`: Retrieves the current widget configuration. - `getState(): State`: Gets the current state of the widget. - `setState(newState: State, err?: string | null): void`: Sets the widget's state. - `reset(newState?: State, err?: string | null): void`: Resets the widget to a new state. - `show(): void`: Makes the widget visible. - `hide(): void`: Hides the widget. - `updateUI(): void`: Forces an update of the widget's user interface. ``` -------------------------------- ### NPM Scripts Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Defines the scripts available for running the project, including development server, build, linting, and previewing the production build. These scripts leverage Vite and TypeScript. ```json { "scripts": { "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint . --ext ts,tsx ...", "preview": "vite preview" } } ``` -------------------------------- ### Configuration Interface Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/04-types-and-interfaces.md The complete Configuration object passed to the ALTCHA widget, defining all customizable options for its behavior and appearance. ```APIDOC ## Configuration Interface The complete Configuration object passed to the ALTCHA widget: ```typescript interface Configuration { // Audio and language settings audioChallengeLanguage: string // Automatic verification trigger behavior auto: 'off' | 'onfocus' | 'onload' | 'onsubmit' // Bar display positioning barPlacement: 'bottom' | 'top' // Challenge data - URL string or Challenge object challenge: Challenge | string | null // Code-based challenge (image and optional audio) codeChallenge: CodeChallenge | null // Code challenge UI layout codeChallengeDisplay: 'standard' | 'overlay' | 'bottomsheet' // Network credentials handling credentials: RequestCredentials | null // Debug logging to console debug: boolean // Prevent code challenge modal from auto-focusing disableAutoFocus: boolean // Widget visual display mode display: 'standard' | 'bar' | 'floating' | 'overlay' | 'invisible' // Custom fetch function for HTTP requests fetch: typeof fetch // Floating UI anchor element/selector floatingAnchor: string | HTMLElement | null // Floating widget offset from anchor (pixels) floatingOffset: number // default: 12 // Keep floating widget visible after verification floatingPersist: boolean | 'focus' // Floating widget preferred position floatingPlacement: 'auto' | 'bottom' | 'top' // Hide "ALTCHA" attribution link hideFooter: boolean // Hide ALTCHA logo icon hideLogo: boolean // Collect pointer/scroll events for HIS (Human Interaction Signature) humanInteractionSignature: boolean // ISO alpha-2 language code for localization language: string // Minimum verification time in milliseconds (artificial delay) minDuration: number // default: 500 // Mock error for UI testing mockError: boolean // Hidden input field name name: string // default: 'altcha' // CSS selector for overlay content mirroring overlayContent: string | null // Popover placement (top/bottom) popoverPlacement: 'auto' | 'bottom' | 'top' // Restart verification with fewer workers on OOM error retryOnOutOfMemoryError: boolean // Include other form field values in server verification serverVerificationFields: boolean // Include user timezone in server verification serverVerificationTimeZone: boolean // Set verification payload in cookie instead of form field setCookie: SetCookieOptions | null // Mock successful verification (testing) test: boolean // PoW verification timeout (milliseconds) timeout: number // default: 90000 // Widget interaction element style type: 'native' | 'checkbox' | 'switch' // Custom HTML5 validation message validationMessage: string // Custom verification handler function verifyFunction: ((payload: string, code?: string) => Promise) | null // Server-side verification endpoint URL verifyUrl: string | null // Number of Web Workers for PoW calculations workers: number } ``` ``` -------------------------------- ### configure() Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Updates the widget's configuration settings. This method can be called multiple times to modify various aspects of the widget's behavior and appearance. ```APIDOC ## configure() ### Description Updates widget configuration (can be called multiple times). ### Signature ```typescript configure(config: Partial): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `config` (`Partial`) - **Type**: `Partial` - **Required**: Yes - **Description**: Configuration object with properties to update See [Configuration Guide](05-configuration-guide.md) for all available configuration options. ### Response #### Success Response - **Type**: `Promise` Resolves when configuration is applied. #### Throws Rejects if configuration is invalid. ### Usage Examples **Update challenge URL:** ```typescript await widget.configure({ challenge: 'https://api.example.com/challenge' }) ``` **Update multiple settings:** ```typescript await widget.configure({ debug: false, display: 'floating', language: 'en', minDuration: 1000, }) ``` **Enable test mode:** ```typescript await widget.configure({ test: true }) ``` **Change display mode:** ```typescript await widget.configure({ display: 'overlay' }) ``` ``` -------------------------------- ### Include Build and ESLint Configurations Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Specifies the files to be included in the TypeScript compilation for build and linting configurations. ```json "include": ["vite.config.ts", ".eslintrc.cjs"] ``` -------------------------------- ### Import Logo Assets in React Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/03-app-component.md Imports the necessary logo image files for Vite and React. Ensure the paths to these assets are correct relative to the current file. ```typescript import reactLogo from './assets/react.svg' import viteLogo from '/vite.svg' ``` -------------------------------- ### Before: Using Widget Directly Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/09-react-hooks-and-patterns.md This code demonstrates the older approach of directly querying the DOM for a widget and attaching an event listener. It highlights the difficulty in accessing the payload outside the event handler. ```typescript function MyForm() { useEffect(() => { const widget = document.querySelector('altcha-widget') let payload: string | null = null widget?.addEventListener('statechange', (ev: CustomEvent) => { payload = ev.detail.payload || null }) }, []) const handleSubmit = () => { // payload not accessible here without global variable } } ``` -------------------------------- ### Check Current Display Mode Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Use `getConfiguration()` to fetch the current settings and check the `display` mode of the widget. This is helpful for conditional logic based on the widget's appearance. ```typescript const config = widget.getConfiguration() if (config.display === 'floating') { console.log('Widget is in floating mode') } ``` -------------------------------- ### New Utility Function Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Demonstrates creating a simple utility function in a TypeScript file. ```typescript export const myFunction = (x: number) => x * 2 ``` -------------------------------- ### ChallengeParameters Interface Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/04-types-and-interfaces.md Defines the parameters required for a proof-of-work challenge, including algorithm, nonce, salt, and various computational cost settings. ```APIDOC ## ChallengeParameters Interface ```typescript interface ChallengeParameters { algorithm: string nonce: string salt: string cost: number keyLength: number keyPrefix: string keySignature?: string memoryCost?: number parallelism?: number expiresAt?: number data?: Record } ``` **Fields:** | Field | Type | Required | Description | |-------|------|----------|-------------| | `algorithm` | `string` | Yes | Hash algorithm name (e.g., 'argon2i', 'scrypt', 'sha1') | | `nonce` | `string` | Yes | Unique challenge nonce value | | `salt` | `string` | Yes | Salt for hash computation | | `cost` | `number` | Yes | Computational cost parameter | | `keyLength` | `number` | Yes | Derived key length in bytes | | `keyPrefix` | `string` | Yes | Prefix for verification hash | | `keySignature` | `string` | No | Optional signature of key for verification | | `memoryCost` | `number` | No | Memory cost for algorithms like Argon2 | | `parallelism` | `number` | No | Parallelism parameter for Argon2 | | `expiresAt` | `number` | No | Unix timestamp when challenge expires | | `data` | `Record` | No | Additional metadata associated with challenge | ``` -------------------------------- ### ALTCHA Data Flow Overview Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/00-index.md Illustrates the sequence of events from user interaction with the ALTCHA widget to server-side verification. ```text User Interaction ↓ (Web Component) ↓ statechange CustomEvent ↓ useEffect listener in Altcha component ↓ setState(payload) or onStateChange callback ↓ Parent component receives update ↓ Render with payload/state ↓ Submit with payload to server ↓ Server verifies with ALTCHA ``` -------------------------------- ### Production Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Configure Altcha for production with API endpoints for challenge and verification, and set credentials for same-origin requests. ```typescript { challenge: 'https://api.example.com/challenge', verifyUrl: 'https://api.example.com/verify', test: false, debug: false, credentials: 'same-origin', serverVerificationFields: true, serverVerificationTimeZone: true, } ``` -------------------------------- ### ALTCHA Widget Methods Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/00-index.md Lists the available methods for interacting with the ALTCHA widget instance. These methods allow for verification, configuration, state management, and UI control. ```typescript verify(options?: VerifyOptions): Promise ``` ```typescript configure(config: Partial): Promise ``` ```typescript getConfiguration(): Configuration ``` ```typescript getState(): State ``` ```typescript setState(newState: State, err?: string | null): void ``` ```typescript reset(newState?: State, err?: string | null): void ``` ```typescript show(): void ``` ```typescript hide(): void ``` ```typescript updateUI(): void ``` -------------------------------- ### Enable Test Mode via Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Configure the widget to enable test mode by setting the `test` option to `true` using the `configure()` method. This is useful for development and testing purposes. ```typescript await widget.configure({ test: true }) ``` -------------------------------- ### Show Widget Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Makes the widget visible. Use this when the widget needs to be displayed after being hidden or during specific user interactions. ```typescript widget.show() ``` ```typescript form.addEventListener('focus', () => { widget.show() }) ``` -------------------------------- ### Vite Build Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md This TypeScript file configures the Vite build tool, including enabling the React plugin for JSX and Fast Refresh. It sets up the development server and build output. ```typescript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], }) ``` -------------------------------- ### Development Dependencies Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Specifies the development-time dependencies required for building, linting, and testing the project. This includes Vite, TypeScript, ESLint, and React-specific plugins. ```json { "devDependencies": { "@types/react": "19.0.12", "@types/react-dom": "19.0.4", "@typescript-eslint/eslint-plugin": "^7.18.0", "@typescript-eslint/parser": "^7.18.0", "@vitejs/plugin-react": "^4.7.0", "eslint": "^8.57.1", "eslint-plugin-react-hooks": "^4.6.2", "eslint-plugin-react-refresh": "^0.4.26", "typescript": "^5.9.3", "vite": "^6.4.3" } } ``` -------------------------------- ### ALTCHA ChallengeParameters Interface Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/04-types-and-interfaces.md Defines the parameters required for a proof-of-work challenge, including algorithm, nonce, salt, and computational costs. ```typescript interface ChallengeParameters { algorithm: string nonce: string salt: string cost: number keyLength: number keyPrefix: string keySignature?: string memoryCost?: number parallelism?: number expiresAt?: number data?: Record } ``` -------------------------------- ### Enable Project References Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Enables incremental compilation when using Project References in TypeScript. ```json "composite": true ``` -------------------------------- ### Implement Custom Fetch Implementation Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Provide a custom fetch function using the 'fetch' option for network requests, allowing for custom logic like logging. ```typescript { fetch: async (url, options) => { // Custom fetch with logging console.log('Fetching:', url) return window.fetch(url, options) } } ``` -------------------------------- ### Import ALTCHA Package Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/08-integration-guide.md Import the necessary ALTCHA modules and types in your main application file or component. Ensure these imports are placed correctly for the package to be recognized. ```typescript import 'altcha' import type { WidgetAttributes, WidgetMethods } from 'altcha/types' ``` -------------------------------- ### WidgetMethods Interface Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/04-types-and-interfaces.md Provides an interface for directly interacting with the Altcha widget instance. These methods allow for dynamic control and querying of the widget's state and configuration. ```APIDOC ## WidgetMethods Interface ### Description Methods available on the `` element for direct interaction. ### Methods #### `configure` - **Description**: Update widget configuration. - **Signature**: `(config: Partial) => Promise` #### `getConfiguration` - **Description**: Get current configuration. - **Signature**: `() => Configuration` #### `getState` - **Description**: Get current widget state. - **Signature**: `() => State` #### `hide` - **Description**: Hide the widget. - **Signature**: `() => void` #### `reset` - **Description**: Reset to state, optionally with error. - **Signature**: `(newState?: State, err?: string | null) => void` #### `setState` - **Description**: Set widget state. - **Signature**: `(newState: State, err?: string | null) => void` #### `show` - **Description**: Show the widget. - **Signature**: `() => void` #### `updateUI` - **Description**: Refresh widget visual. - **Signature**: `() => void` #### `verify` - **Description**: Initiate verification. - **Signature**: `(options?: VerifyOptions) => Promise` ``` -------------------------------- ### Update Widget Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Use the `configure()` method to update specific settings of the ALTCHA widget. This method accepts a partial configuration object and can be called multiple times. ```typescript await widget.configure({ challenge: 'https://api.example.com/challenge' }) ``` -------------------------------- ### Module Resolution: Local File Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/11-file-structure-and-modules.md Details how Vite resolves local file imports, checking for files and then directories with index files. ```javascript import X from './file' ``` -------------------------------- ### Configure Challenge via URL Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Set the `challenge` property to a string containing the URL from which to fetch challenge data. ```typescript { challenge: 'https://api.example.com/challenge' } ``` -------------------------------- ### TypeScript Include and References Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Specifies that all files within the 'src/' directory should be included in the compilation and references the tsconfig.node.json for build tool configurations. ```json "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] ``` -------------------------------- ### Access Vite Environment Variables Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Demonstrates how to access and use Vite environment variables with proper TypeScript typing. ```typescript // ✓ Can access Vite env vars with proper typing const isDev = import.meta.env.DEV const appName = import.meta.env.VITE_APP_NAME ``` -------------------------------- ### Vite Client Type Reference Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Loads type definitions for Vite, enabling access to Vite-specific environment variables like import.meta.env. ```typescript /// ``` -------------------------------- ### Configure Challenge via Object Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Provide a challenge object directly to the `challenge` property for detailed challenge parameters. ```typescript { challenge: { parameters: { algorithm: 'argon2i', nonce: '...', salt: '...', cost: 3, keyLength: 32, keyPrefix: 'v1=' } } } ``` -------------------------------- ### ALTCHA Configuration Options Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/00-index.md Details common configuration options for the ALTCHA widget. These control aspects like challenge data, verification URL, display mode, and testing behavior. ```typescript challenge: Challenge | string | null ``` ```typescript verifyUrl: string | null ``` ```typescript display: 'standard' | 'bar' | ... ``` ```typescript test: boolean ``` ```typescript debug: boolean ``` -------------------------------- ### Default Component Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/02-altcha-component-api.md Shows the default configuration object for the ALTCHA component. In production, ensure 'challenge', 'verifyUrl', and 'test: false' are set. ```typescript { debug: true, // Enable console logging test: true // Use test mode (mocks verification) } ``` -------------------------------- ### Import ALTCHA Widget Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/README.md Import the ALTCHA widget package into your main application file (e.g., src/main.tsx). This makes the custom element available. ```tsx // src/main.tsx or appropriate file import 'altcha'; ``` -------------------------------- ### Chaining Widget Methods Sequentially Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Use async/await to chain multiple widget methods in sequence. Ensure that asynchronous operations like configure and verify complete before proceeding. ```typescript await widget.configure({ test: true }) const result = await widget.verify() widget.setState(result ? 'verified' : 'error') widget.updateUI() ``` -------------------------------- ### Implementing Widget Error Recovery Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/06-widget-methods.md Use a try-catch block to handle potential errors during verification or state updates. This pattern allows for graceful error reporting and UI updates. ```typescript try { const result = await widget.verify() if (result) { widget.setState('verified') } else { widget.setState('error', 'Verification cancelled') } } catch (error) { widget.setState('error', 'Network error: ' + error.message) widget.updateUI() } ``` -------------------------------- ### Node TypeScript Configuration Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md Configuration for Node.js environments, enabling Project References and module resolution for Vite and ESLint. ```json { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts", ".eslintrc.cjs"] } ``` -------------------------------- ### Root tsconfig.json with Project References Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/10-typescript-guide.md The root tsconfig.json uses Project References to define separate compilation contexts for application code and build configurations. ```json { "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" } ] } ``` -------------------------------- ### Configure Web Workers for Proof-of-Work Source: https://github.com/altcha-org/altcha-starter-react-ts/blob/main/_autodocs/05-configuration-guide.md Specify the number of Web Workers for proof-of-work calculations using the 'workers' option. More workers can speed up calculations but increase CPU usage. ```typescript { workers: 4 } ```