{"id":15011543,"url":"https://github.com/ixnas/altcha-dotnet","last_synced_at":"2025-04-12T03:31:05.567Z","repository":{"id":235911010,"uuid":"790358530","full_name":"ixnas/altcha-dotnet","owner":"ixnas","description":"C# implementation of the ALTCHA challenge.","archived":false,"fork":false,"pushed_at":"2025-03-23T17:18:23.000Z","size":182,"stargazers_count":22,"open_issues_count":0,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-25T23:23:08.525Z","etag":null,"topics":["altcha","anti-spam","asp-net","asp-net-core","captcha","csharp","dotnet","dotnet-core","dotnet-framework","dotnet-standard","dotnet-standard2","library","nuget","nuget-package","spam","web"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-2-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ixnas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE-ALTCHA.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-04-22T18:26:51.000Z","updated_at":"2025-03-22T21:58:35.000Z","dependencies_parsed_at":"2024-09-20T06:00:55.957Z","dependency_job_id":"83e48742-4275-403d-8514-fafe1d17a08b","html_url":"https://github.com/ixnas/altcha-dotnet","commit_stats":{"total_commits":28,"total_committers":1,"mean_commits":28.0,"dds":0.0,"last_synced_commit":"d0b3626a11c354d864a60d34d9dcda79efa41c50"},"previous_names":["ixnas/altcha-dotnet"],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ixnas%2Faltcha-dotnet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ixnas%2Faltcha-dotnet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ixnas%2Faltcha-dotnet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ixnas%2Faltcha-dotnet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ixnas","download_url":"https://codeload.github.com/ixnas/altcha-dotnet/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248512517,"owners_count":21116616,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["altcha","anti-spam","asp-net","asp-net-core","captcha","csharp","dotnet","dotnet-core","dotnet-framework","dotnet-standard","dotnet-standard2","library","nuget","nuget-package","spam","web"],"created_at":"2024-09-24T19:41:13.746Z","updated_at":"2025-04-12T03:31:05.556Z","avatar_url":"https://github.com/ixnas.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Altcha.NET\n\n[![Build status](https://ci.sjoerdscheffer.nl/job/Altcha.NET/job/main/badge/icon?style=flat-square)](https://ci.sjoerdscheffer.nl/job/Altcha.NET/job/main/)\n[![Nuget version](https://ci.sjoerdscheffer.nl/job/Altcha.NET/job/main/badge/icon?config=nugetBadge\u0026style=flat-square)](https://www.nuget.org/packages/Ixnas.AltchaNet)\n\nC# implementation of the [ALTCHA](http://altcha.org) challenge.\n\n**Features**\n\n- Compatible with the [ALTCHA client-side widget](https://altcha.org/docs/website-integration/#using-altcha-widget)\n- Independent from ASP.NET (Core)\n- Generates and validates self-hosted challenges\n- Validates challenges from [ALTCHA's public API](https://altcha.org/docs/api/)\n- Validates forms that were spam-filtered by [ALTCHA's spam filter API](https://altcha.org/docs/api/spam-filter-api/)\n- Solves remotely hosted challenges, enabling [machine-to-machine ALTCHA](https://altcha.org/docs/m2m-altcha/)\n- Replay attack prevention by denying previously verified challenges\n- Expiring challenges\n\n## Contents\n\n- [Installation](#installation)\n- [Using self-hosted challenges](#using-self-hosted-challenges)\n    - [Set up](#set-up)\n        - [Key](#key)\n        - [Store](#store)\n    - [Usage](#usage)\n        - [Generating a challenge](#generating-a-challenge)\n        - [Validating a response](#validating-a-response)\n- [Verifying challenges from ALTCHA's API](#verifying-challenges-from-altchas-api)\n    - [Set up](#set-up-1)\n    - [Usage](#usage-1)\n        - [Validating a regular response](#validating-a-regular-response)\n        - [Validating a spam filtered form](#validating-a-spam-filtered-form)\n- [Solving challenges](#solving-challenges)\n    - [Set up](#set-up-2)\n    - [Usage](#usage-2)\n- [Example](#example)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Installation\n\nThis library is available on NuGet, so you can add it to your project as follows:\n\n```\ndotnet add package Ixnas.AltchaNet\n```\n\n## Using self-hosted challenges\n\n### Set up\n\nFirst make sure you've [set up the front-end widget](https://altcha.org/docs/website-integration/#using-altcha-widget)\nto use your challenge endpoint.\n\nThe entrypoint of this library contains a service builder for self-hosted configurations.\nThis builder configures the service that is used to create ALTCHA challenges and validate their responses.\nThe most basic configuration looks like this:\n\n```csharp\nvar altchaService = Altcha.CreateServiceBuilder()\n                          .UseSha256(key)\n                          .UseStore(storeFactory)\n                          .Build();\n```\n\nHere is a description of the different configuration options.\n\n| Method                                                                                                                  | Description                                                                                                                                                                                                                        |\n|-------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `UseStore(Func\u003cIAltchaChallengeStore\u003e storeFactory)`\u003cbr\u003e`UseStore(Func\u003cIAltchaCancellableChallengeStore\u003e storeFactory)` | (Required) Configures a store factory to use for previously verified ALTCHA responses. Used to prevent replay attacks.                                                                                                             |\n| `UseStore(IAltchaChallengeStore store)`\u003cbr\u003e`UseStore(IAltchaCancellableChallengeStore store)`                           | (Required) Configures a store instance to use for previously verified ALTCHA responses. Used to prevent replay attacks.                                                                                                            |\n| `UseSha256(byte[] key)`                                                                                                 | (Required) Configures the SHA-256 algorithm for hashing and signing. Must be 64 bytes long. Currently the only supported algorithm.                                                                                                |\n| `SetComplexity(AltchaComplexity complexity)`\u003cbr\u003e`SetComplexity(int min, int max)`                                       | (Optional) Overrides the default complexity to tweak the amount of computational effort a client has to put in. See [ALTCHA's documentation](https://altcha.org/docs/complexity/) for more information (default 50,000 - 100,000). |\n| `SetExpiry(AltchaExpiry expiry)`\u003cbr\u003e`SetExpiryInSeconds(int expiryInSeconds)`                                           | (Optional) Overrides the default time it takes for a challenge to expire (default 120 seconds).                                                                                                                                    |\n| `UseInMemoryStore()`                                                                                                    | Configures a simple in-memory store for previously verified ALTCHA responses. Should only be used for testing purposes.                                                                                                            |\n| `Build()`                                                                                                               | Returns a new configured service instance.                                                                                                                                                                                         |\n\n#### Key\n\nThe library requires a key to sign and verify ALTCHA challenges.\nYou can use a random number generator from .NET to create one for you:\n\n```csharp\nvar key = new byte[64];\nusing (var rng = RandomNumberGenerator.Create())\n{\n    rng.GetBytes(key);\n}\n```\n\n#### Store\n\nThe library requires a store implementation to store previously verified challenge responses.\nYou can use anything persistent, like a database or a file.\nAs long as it implements the `IAltchaChallengeStore` or the `IAltchaCancellableChallengeStore` interface, it will work.\n\nFor persistent (I/O-bound) storage implementations, you should probably implement `IAltchaCancellableChallengeStore`\nwhich supports `CancellationToken`s.\n\nYou can use `expiryUtc` to periodically remove expired challenges from your store.\n\nAs an example, the bundled in-memory store looks similar to this:\n\n```csharp\npublic class InMemoryStore : IAltchaChallengeStore\n{\n    private class StoredChallenge\n    {\n        public string Challenge { get; set; }\n        public DateTimeOffset ExpiryUtc { get; set; }\n    }\n\n    private readonly List\u003cStoredChallenge\u003e _stored = new List\u003cStoredChallenge\u003e();\n\n    public Task Store(string challenge, DateTimeOffset expiryUtc)\n    {\n        var challengeToStore = new StoredChallenge\n        {\n            Challenge = challenge,\n            ExpiryUtc = expiryUtc\n        };\n        _stored.Add(challengeToStore);\n        return Task.CompletedTask;\n    }\n\n    public Task\u003cbool\u003e Exists(string challenge)\n    {\n        _stored.RemoveAll(storedChallenge =\u003e storedChallenge.ExpiryUtc \u003c= DateTimeOffset.UtcNow);\n        var exists = _stored.Exists(storedChallenge =\u003e storedChallenge.Challenge == challenge);\n        return Task.FromResult(exists);\n    }\n}\n```\n\nIf you're using a short-lived object to access your database (like a request-scoped Entity Framework DbContext), it is\nrecommended to provide a factory function for the store instead of an instance.\n\n### Usage\n\n#### Generating a challenge\n\nTo generate a challenge:\n\n```csharp\nvar challenge = altchaService.Generate();\n```\n\nThe `challenge` object can be serialized to JSON for the client to use.\nRead [ALTCHA's documentation](https://altcha.org/docs/website-integration/#using-altcha-widget) on how to use such a\nJSON object.\n\nIt's possible to override configuration options by passing an `AltchaGenerateChallengeOverrides` object.\nThis can be useful when implementing a [dynamic complexity](https://altcha.org/docs/complexity/#recommended-practices)\nstrategy, for example.\n\n```csharp\nvar overrides = new AltchaGenerateChallengeOverrides\n{\n    Complexity = new AltchaComplexity(200000, 300000),\n    Expiry = AltchaExpiry.FromSeconds(300),\n};\nvar challenge = altchaService.Generate(overrides);\n```\n\nOnly the properties that are set will affect the generation, and only for this single call.\n\n#### Validating a response\n\nTo validate a response:\n\n```csharp\nvar validationResult = await altchaService.Validate(altcha, cancellationToken);\nif (!validationResult.IsValid)\n{\n    _logger.LogInformation(validationResult.ValidationError.Message);\n    /* ... */\n}\n```\n\nThe `altcha` parameter can either be a base64-encoded JSON string (like the raw value of the `altcha` field in a\nsubmitted form), or an already decoded and deserialized `AltchaResponse` object.\n\nThe `cancellationToken` parameter can be passed if the service was set up with a `IAltchaCancellableChallengeStore`.\nThe cancellation token can cancel queries and updates to the store implementation.\n\n## Verifying challenges from ALTCHA's API\n\n### Set up\n\nFirst make sure you've [set up the front-end widget](https://altcha.org/docs/api/challenge-api/#using-with-the-widget)\nto use the API.\n\nThe entrypoint of this library contains a different service builder for integrating with ALTCHA's API.\nThe most basic configuration looks like this:\n\n```csharp\nvar altchaApiService = Altcha.CreateApiServiceBuilder()\n                             .UseApiSecret(secret)\n                             .UseStore(storeFactory)\n                             .Build();\n```\n\nHere is a description of the different configuration options.\n\n| Method                                                                                                                  | Description                                                                                                               |\n|-------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|\n| `UseStore(Func\u003cIAltchaChallengeStore\u003e storeFactory)`\u003cbr\u003e`UseStore(Func\u003cIAltchaCancellableChallengeStore\u003e storeFactory)` | (Required) Configures a store factory to use for previously verified ALTCHA responses. Used to prevent replay attacks.    |\n| `UseStore(IAltchaChallengeStore store)`\u003cbr\u003e`UseStore(IAltchaCancellableChallengeStore store)`                           | (Required) Configures a store instance to use for previously verified ALTCHA responses. Used to prevent replay attacks.   |\n| `UseApiSecret(string secret)`                                                                                           | (Required) Configures the API secret used to validate challenges from ALTCHA's API. Starts with either \"sec_\" or \"_csec\". |\n| `SetMaxSpamFilterScore(double score)`                                                                                   | (Optional) Overrides the default maximum score that a spam filtered form may have before it's rejected (default 2).       |\n| `UseInMemoryStore()`                                                                                                    | Configures a simple in-memory store for previously verified ALTCHA responses. Should only be used for testing purposes.   |\n| `Build()`                                                                                                               | Returns a new configured service instance.                                                                                |\n\nThe store uses the [same interface](#store) as it does for the self-hosted service.\nYou can even use the same instance if you like.\n\n### Usage\n\n#### Validating a regular response\n\nTo validate a regular response:\n\n```csharp\nvar validationResult = await altchaApiService.Validate(altcha, cancellationToken);\nif (!validationResult.IsValid)\n{\n    _logger.LogInformation(validationResult.ValidationError.Message);\n    /* ... */\n}\n```\n\nThis works the same way as [self-hosted validation](#validating-a-response).\nChallenges generated by the self-hosted service can not be validated by the API service, or vice versa.\n\n#### Validating a spam filtered form\n\nTo validate a spam filtered form, you need an object that represents the form fields as public string properties.\nBy default, the library looks for a public string property named `Altcha` that should contain the raw value from\nthe `altcha` field in a submitted form.\nA form class could look like this:\n\n```csharp\npublic class ExampleForm\n{\n    public string Altcha { get; set; }\n    public string Email { get; set; }\n    public string Text { get; set; }\n}\n```\n\nTo validate the form:\n\n```csharp\nvar validationResult = await altchaApiService.ValidateSpamFilteredForm(form, cancellationToken);\nif (!validationResult.IsValid)\n{\n    _logger.LogInformation(validationResult.ValidationError.Message);\n    /* ... */\n}\n\nif (!validationResult.PassedSpamFilter)\n    /* ... */\n```\n\nIf you prefer to use a different property for the ALTCHA payload, you can use a member expression to select it:\n\n```csharp\nvar validationResult = await altchaApiService.ValidateSpamFilteredForm(form, cancellationToken, x =\u003e x.AnotherProperty);\n```\n\nThe result's `IsValid` property tells you whether the form data, verification data and the signature are valid.\nYou should probably reject the form submission if this is not the case.\nThe `ValidationError` property contains more details on why the validation failed.\n\nThe result's `PassedSpamFilter` property tells you whether the form data successfully passed through the spam filter.\nYou might want to keep the form submission and mark it as spam in your application for manual approval.\n\n## Solving challenges\n\n### Set up\n\nThe entrypoint of this library contains a builder for creating solver instances. The most basic configuration looks like\nthis:\n\n```csharp\nvar altchaSolver = Altcha.CreateSolverBuilder()\n                         .Build();\n```\n\nHere is a description of the different configuration options.\n\n| Method           | Description                                                                     |\n|------------------|---------------------------------------------------------------------------------|\n| `IgnoreExpiry()` | (Optional) Disables checking for expiry before attempting to solve a challenge. |\n| `Build()`        | Returns a new configured solver instance.                                       |\n\n### Usage\n\nTo solve a challenge, first make sure you have a deserialized `AltchaChallange` object to solve. Then you can solve the\nchallenge as follows:\n\n```csharp\nvar solverResult = altchaSolver.Solve(challenge);\n\nif (!solverResult.Success)\n{\n    _logger.LogInformation(solverResult.Error.Message);\n    /* ... */\n}\n\nvar formWithAltcha = new\n{\n    SomeFormField = \"some text\",\n    Altcha = solverResult.Altcha\n};\n```\n\nThis example attaches the solution from `solverResult.Altcha` to a form object as the \"altcha\" field.\n\n## Example\n\nThe `AspNetCoreExample` project contains a few examples for generating, solving and validating challenges.\n\n## Contributing\n\nBug reports, fixes, ideas and suggestions are always welcome! Feel free to reach out by creating new issues, and I'll\ntry to respond as soon as I can.\n\n## License\n\nSee [LICENSE.txt](https://github.com/ixnas/altcha-dotnet/blob/main/LICENSE.txt)\n\nSee [LICENSE-ALTCHA.txt](https://github.com/ixnas/altcha-dotnet/blob/main/LICENSE-ALTCHA.txt) for ALTCHA's original\nlicense.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fixnas%2Faltcha-dotnet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fixnas%2Faltcha-dotnet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fixnas%2Faltcha-dotnet/lists"}