@credithub/jurischain-node 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 CreditHub / Lucas Fernando Amorim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,220 @@
1
+ <div align="center">
2
+
3
+ # @credithub/jurischain-node
4
+
5
+ **Native Node.js binding for [JurisChain](https://github.com/credithub/jurischain) — a SHA3-256 Proof-of-Work CAPTCHA.**
6
+ Challenge the *terminals*, not the *humans*. No tracking, no third parties, no image grids.
7
+
8
+ [![npm](https://img.shields.io/npm/v/@credithub/jurischain-node?logo=npm&color=cb3837)](https://www.npmjs.com/package/@credithub/jurischain-node)
9
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
10
+ [![Node](https://img.shields.io/badge/node-%3E%3D14-339933?logo=node.js&logoColor=white)](package.json)
11
+
12
+ </div>
13
+
14
+ ---
15
+
16
+ ## TL;DR
17
+
18
+ ```bash
19
+ npm install @credithub/jurischain-node
20
+ ```
21
+
22
+ ```js
23
+ const crypto = require('crypto');
24
+ const { Jurischain } = require('@credithub/jurischain-node');
25
+
26
+ // 1. Server issues a challenge: a random seed + a difficulty (1–255)
27
+ const seed = crypto.randomBytes(16).toString('hex');
28
+ const difficulty = 10;
29
+
30
+ // 2. Client burns CPU solving the Proof-of-Work
31
+ const client = new Jurischain(difficulty, seed);
32
+ while (!client.solveStep()); // ~2^difficulty SHA3-256 hashes
33
+ const solution = client.readChallenge();
34
+
35
+ // 3. Server verifies in O(1) — a single hash comparison
36
+ const server = new Jurischain(difficulty, seed);
37
+ server.challengeResponse(solution);
38
+ console.log(server.verify()); // → true
39
+ ```
40
+
41
+ That's the whole API. Keep reading for the *why* and the details.
42
+
43
+ ---
44
+
45
+ ## Why?
46
+
47
+ Traditional captchas (reCAPTCHA, hCaptcha) track users, sell data, and depend on
48
+ external servers. JurisChain flips the model: instead of challenging *humans*, it
49
+ challenges the *machine*.
50
+
51
+ A client must solve a SHA3-256 Proof-of-Work puzzle before its request is accepted.
52
+ This makes automated abuse computationally expensive while keeping the experience
53
+ seamless — no image grids, no cookies, no surveillance. Verification on the server
54
+ is a single hash comparison, so it costs you almost nothing.
55
+
56
+ This package is the **native Node.js addon** (C++ via [NAN](https://github.com/nodejs/nan) +
57
+ [node-gyp](https://github.com/nodejs/node-gyp)) wrapping the same header-only C core
58
+ that powers the browser, PHP, and Python bindings — so the client and server speak
59
+ exactly the same protocol, bit for bit.
60
+
61
+ ## Installation
62
+
63
+ ```bash
64
+ npm install @credithub/jurischain-node
65
+ ```
66
+
67
+ This is a **native addon**: it compiles from source on `npm install` via `node-gyp`.
68
+ You need a C++ toolchain and Python 3 on the build machine:
69
+
70
+ | Platform | Prerequisites |
71
+ |---|---|
72
+ | **Linux** | `build-essential` (gcc/g++, make) and `python3` |
73
+ | **macOS** | Xcode Command Line Tools (`xcode-select --install`) |
74
+ | **Windows** | [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/) + Python 3 |
75
+
76
+ Requires **Node.js ≥ 14**.
77
+
78
+ ## How It Works
79
+
80
+ ```
81
+ ┌──────────┐ seed + difficulty ┌──────────┐
82
+ │ Server │ ───────────────────────────▸ │ Client │
83
+ │ │ │ │
84
+ │ │ │ SHA3-256 │
85
+ │ │ │ PoW loop │
86
+ │ │ solution hash │ ⏳ │
87
+ │ verify() │ ◂─────────────────────────── │ │
88
+ └──────────┘ └──────────┘
89
+ ```
90
+
91
+ 1. **Server** generates a random `seed` and picks a `difficulty` (1–255).
92
+ 2. **Client** receives `{ seed, difficulty }` and iterates SHA3-256 until the
93
+ result has `difficulty` leading zero bits.
94
+ 3. **Client** sends the solution hash back.
95
+ 4. **Server** verifies in O(1).
96
+
97
+ Higher difficulty = exponentially more work for the client, linearly tunable by
98
+ the server. See the [main project README](https://github.com/credithub/jurischain#readme)
99
+ for the full design rationale.
100
+
101
+ ## API
102
+
103
+ The package exports a single class, `Jurischain`.
104
+
105
+ ```js
106
+ const { Jurischain } = require('@credithub/jurischain-node');
107
+ // ESM / TypeScript: import { Jurischain } from '@credithub/jurischain-node';
108
+ ```
109
+
110
+ | Member | Returns | Description |
111
+ |---|---|---|
112
+ | `new Jurischain(difficulty, seed)` | instance | Create a challenge. `difficulty` is an integer **1–255**; `seed` is a **non-empty string**. Throws `TypeError` / `RangeError` on bad input. |
113
+ | `solveStep()` | `boolean` | Run **one** PoW iteration (a single SHA3-256 hash). Returns `true` once the challenge is solved. Call it in a loop on the client. |
114
+ | `readChallenge()` | `string` | The current state as a 64-character hex string. After the challenge is solved this is the **solution** to send to the server. |
115
+ | `challengeResponse(response)` | `boolean` | Load a client's 64-character hex solution into the context so it can be checked. Throws `RangeError` if the length isn't exactly 64, or `Error` on invalid hex. |
116
+ | `verify()` | `boolean` | `true` if the current state satisfies the difficulty. **Run this server-side.** |
117
+
118
+ > **Note:** `solveStep()` runs a tight, CPU-bound loop and blocks the event loop
119
+ > while it runs. For low difficulties this is microseconds; for high difficulties,
120
+ > solve inside a [Worker thread](https://nodejs.org/api/worker_threads.html) so you
121
+ > don't stall your server.
122
+
123
+ ## Client / Server Example
124
+
125
+ A minimal [Express](https://expressjs.com/) flow: the server hands out challenges,
126
+ the client solves them, the server verifies.
127
+
128
+ ```js
129
+ const crypto = require('crypto');
130
+ const express = require('express');
131
+ const { Jurischain } = require('@credithub/jurischain-node');
132
+
133
+ const app = express();
134
+ app.use(express.json());
135
+
136
+ const DIFFICULTY = 12;
137
+ const issued = new Map(); // seed -> expiry (use Redis/etc. in production)
138
+
139
+ // 1. Hand out a fresh, single-use challenge
140
+ app.get('/challenge', (req, res) => {
141
+ const seed = crypto.randomBytes(16).toString('hex');
142
+ issued.set(seed, Date.now() + 60_000); // valid for 60s
143
+ res.json({ seed, difficulty: DIFFICULTY });
144
+ });
145
+
146
+ // 2. Verify the submitted solution
147
+ app.post('/submit', (req, res) => {
148
+ const { seed, solution } = req.body;
149
+
150
+ // Only accept seeds we issued and haven't seen redeemed (anti-replay)
151
+ const expiry = issued.get(seed);
152
+ if (!expiry || expiry < Date.now()) {
153
+ return res.status(400).json({ ok: false, error: 'unknown or expired seed' });
154
+ }
155
+ issued.delete(seed);
156
+
157
+ const verifier = new Jurischain(DIFFICULTY, seed);
158
+ verifier.challengeResponse(solution);
159
+
160
+ res.json({ ok: verifier.verify() });
161
+ });
162
+
163
+ app.listen(3000);
164
+ ```
165
+
166
+ ```js
167
+ // Client side (Node, browser, or anything that can hash):
168
+ const { seed, difficulty } = await (await fetch('/challenge')).json();
169
+
170
+ const c = new Jurischain(difficulty, seed);
171
+ while (!c.solveStep()); // grind the Proof-of-Work
172
+ const solution = c.readChallenge();
173
+
174
+ const { ok } = await (await fetch('/submit', {
175
+ method: 'POST',
176
+ headers: { 'content-type': 'application/json' },
177
+ body: JSON.stringify({ seed, solution }),
178
+ })).json();
179
+ ```
180
+
181
+ > In the browser, use [`@credithub/jurischain`](https://www.npmjs.com/package/@credithub/jurischain)
182
+ > (WASM/ASM.js) on the client instead of this native addon — both implement the
183
+ > identical protocol, so a browser-solved challenge verifies cleanly here.
184
+
185
+ ## Difficulty Guidelines
186
+
187
+ `difficulty` is the number of leading zero **bits** required in the hash, so the
188
+ expected work grows as `2^difficulty`.
189
+
190
+ | Difficulty | Avg. tries | Typical time | Use case |
191
+ |---|---|---|---|
192
+ | 8–10 | ~500 | < 1s | Login forms, page views |
193
+ | 14–16 | ~30k | 2–5s | API rate limiting |
194
+ | 18–20 | ~200k | 10–30s | Heavy abuse prevention |
195
+
196
+ Tune per endpoint: low for reads, high for sensitive or expensive operations.
197
+
198
+ ## Security Considerations
199
+
200
+ - The **seed must be cryptographically random** and unique per request — reusing
201
+ seeds enables replay attacks. Track issued seeds and accept each only once.
202
+ - **Verify server-side only.** Never trust a client's claim that it solved the
203
+ challenge; recompute with `verify()`.
204
+ - **Tune difficulty per endpoint** — higher for sensitive operations, lower for reads.
205
+ - SHA3-256 is **not reversible** — the server verifies by recomputing, never by
206
+ storing solutions.
207
+
208
+ ## Related Packages
209
+
210
+ | Package | Platform | Install |
211
+ |---|---|---|
212
+ | [`@credithub/jurischain`](https://www.npmjs.com/package/@credithub/jurischain) | Browser (WASM/ASM.js) | `npm install @credithub/jurischain` |
213
+ | **`@credithub/jurischain-node`** | Node.js (native addon) | `npm install @credithub/jurischain-node` |
214
+ | [`credithub/jurischain`](https://github.com/credithub/jurischain/tree/master/bindings/php) | PHP 8 extension | `pie install credithub/jurischain` |
215
+
216
+ ## License
217
+
218
+ [MIT](LICENSE) — created by BIPBOP, maintained by
219
+ [Lucas Fernando Amorim](https://github.com/lfamorim) and
220
+ [CreditHub](https://credithub.com.br).
package/jurischain.h CHANGED
@@ -183,7 +183,7 @@ static inline void *sha3(const void *in, size_t inlen, void *md, int mdlen) {
183
183
 
184
184
  static inline void jurischain_gen(jurischain_ctx_t *challenge, uint8_t d, const void *seed, size_t inlen) {
185
185
  uint8_t rand_hash[HASH_LEN] = { 0, };
186
- if (!challenge || !seed || inlen == 0) return;
186
+ if (!challenge || !seed || inlen == 0 || d == 0) return;
187
187
  memset(challenge, 0, sizeof(jurischain_ctx_t));
188
188
  sha3(seed, inlen, rand_hash, HASH_LEN);
189
189
  memcpy(challenge->seed, rand_hash, sizeof(rand_hash));
@@ -213,11 +213,14 @@ static inline int jurischain_verify(jurischain_ctx_t *challenge) {
213
213
 
214
214
  if (!challenge) return 0;
215
215
 
216
+ d = challenge->payload[HASH_LEN];
217
+
218
+ /* difficulty 0 is a vacuous proof — any response passes; treat as invalid */
219
+ if (d == 0) return 0;
220
+
216
221
  memcpy(hash_concat, challenge->seed, HASH_LEN);
217
222
  memcpy(&hash_concat[HASH_LEN], challenge->payload, HASH_LEN);
218
223
 
219
- d = challenge->payload[HASH_LEN];
220
-
221
224
  sha3(hash_concat, HASH_LEN * 2, response, HASH_LEN);
222
225
 
223
226
  /*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@credithub/jurischain-node",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Native Node.js binding for JurisChain Proof-of-Work CAPTCHA. Challenges terminals instead of humans to mitigate DDoS attacks.",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -11,6 +11,8 @@
11
11
  }
12
12
  },
13
13
  "files": [
14
+ "README.md",
15
+ "LICENSE",
14
16
  "index.js",
15
17
  "index.d.ts",
16
18
  "main.cpp",
@@ -18,7 +20,7 @@
18
20
  "binding.gyp"
19
21
  ],
20
22
  "scripts": {
21
- "prepack": "node -e \"require('fs').copyFileSync('../../include/jurischain.h','jurischain.h')\"",
23
+ "prepack": "node -e \"const fs=require('fs');fs.copyFileSync('../../include/jurischain.h','jurischain.h');fs.copyFileSync('../../LICENSE','LICENSE')\"",
22
24
  "install": "node-gyp rebuild",
23
25
  "rebuild": "node-gyp rebuild",
24
26
  "test": "node -e \"const { Jurischain } = require('.'); const j = new Jurischain(1, 'test'); console.log('OK:', j.readChallenge());\""