xref: /plugin/botmon/captcha.js (revision 12993035b5a997893e460942f7a5343107194a53)
1"use strict";
2/* DokuWiki BotMon Captcha JavaScript */
3/* 22.10.2025 - 0.1.0 - pre-release */
4/* Author: Sascha Leib <ad@hominem.info> */
5
6const $BMCaptcha = {
7
8	init: function() {
9		/* mark the page to contain the captcha styles */
10		document.getElementsByTagName('body')[0].classList.add('botmon_captcha');
11
12		$BMCaptcha.install()
13	},
14
15	install: function() {
16		// find the parent element:
17		let bm_parent = document.getElementsByTagName('body')[0];
18
19		// create the dialog:
20		const dlg = document.createElement('dialog');
21		dlg.setAttribute('closedby', 'none');
22		dlg.setAttribute('open', 'open');
23		dlg.id = 'botmon_captcha_box';
24		dlg.innerHTML = '<h2>Captcha box</h2><p>Checking if you are a human …</p><p></p>';
25
26		// Checkbox:
27		const lbl = document.createElement('label');
28		const cb = document.createElement('input');
29		cb.setAttribute('type', 'checkbox');
30		cb.addEventListener('click', $BMCaptcha._cbCallback);
31		lbl.appendChild(cb);
32		lbl.appendChild(document.createTextNode('I am a human.'));
33
34		dlg.appendChild(lbl);
35
36		bm_parent.appendChild(dlg);
37	},
38
39	/* creates a digest hash for the cookie function */
40	digest: {
41
42		/* simple SHA hash function - adapted from https://geraintluff.github.io/sha256/ */
43		hash: function(ascii) {
44
45			// shortcut:
46			const sha256 = $BMCaptcha.digest.hash;
47
48			// helper function
49			const rightRotate = function(v, a) {
50				return (v>>>a) | (v<<(32 - a));
51			};
52
53			var mathPow = Math.pow;
54			var maxWord = mathPow(2, 32);
55			var lengthProperty = 'length'
56			var i, j;
57			var result = ''
58
59			var words = [];
60			var asciiBitLength = ascii[lengthProperty]*8;
61
62			//* caching results is optional - remove/add slash from front of this line to toggle
63			// Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
64			// (we actually calculate the first 64, but extra values are just ignored)
65			var hash = sha256.h = sha256.h || [];
66			// Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
67			var k = sha256.k = sha256.k || [];
68			var primeCounter = k[lengthProperty];
69			/*/
70			var hash = [], k = [];
71			var primeCounter = 0;
72			//*/
73
74			var isComposite = {};
75			for (var candidate = 2; primeCounter < 64; candidate++) {
76				if (!isComposite[candidate]) {
77					for (i = 0; i < 313; i += candidate) {
78						isComposite[i] = candidate;
79					}
80					hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
81					k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
82				}
83			}
84
85			ascii += '\x80' // Append Ƈ' bit (plus zero padding)
86			while (ascii[lengthProperty]%64 - 56) ascii += '\x00' // More zero padding
87			for (i = 0; i < ascii[lengthProperty]; i++) {
88				j = ascii.charCodeAt(i);
89				if (j>>8) return; // ASCII check: only accept characters in range 0-255
90				words[i>>2] |= j << ((3 - i)%4)*8;
91			}
92			words[words[lengthProperty]] = ((asciiBitLength/maxWord)|0);
93			words[words[lengthProperty]] = (asciiBitLength)
94
95			// process each chunk
96			for (j = 0; j < words[lengthProperty];) {
97				var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
98				var oldHash = hash;
99				// This is now the undefinedworking hash", often labelled as variables a...g
100				// (we have to truncate as well, otherwise extra entries at the end accumulate
101				hash = hash.slice(0, 8);
102
103				for (i = 0; i < 64; i++) {
104					var i2 = i + j;
105					// Expand the message into 64 words
106					// Used below if
107					var w15 = w[i - 15], w2 = w[i - 2];
108
109					// Iterate
110					var a = hash[0], e = hash[4];
111					var temp1 = hash[7]
112						+ (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
113						+ ((e&hash[5])^((~e)&hash[6])) // ch
114						+ k[i]
115						// Expand the message schedule if needed
116						+ (w[i] = (i < 16) ? w[i] : (
117								w[i - 16]
118								+ (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15>>>3)) // s0
119								+ w[i - 7]
120								+ (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2>>>10)) // s1
121							)|0
122						);
123					// This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
124					var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
125						+ ((a&hash[1])^(a&hash[2])^(hash[1]&hash[2])); // maj
126
127					hash = [(temp1 + temp2)|0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()
128					hash[4] = (hash[4] + temp1)|0;
129				}
130
131				for (i = 0; i < 8; i++) {
132					hash[i] = (hash[i] + oldHash[i])|0;
133				}
134			}
135
136			for (i = 0; i < 8; i++) {
137				for (j = 3; j + 1; j--) {
138					var b = (hash[i]>>(j*8))&255;
139					result += ((b < 16) ? 0 : '') + b.toString(16);
140				}
141			}
142			return result;
143		}
144	},
145
146	_cbCallback: function(e) {
147		if (e.target.checked) {
148			//document.getElementById('botmon_captcha_box').close();
149
150			// make a hash for the cookie:
151			const seed = document._botmon.seed || '';
152			const extIp = document._botmon.ip || '0.0.0.0';
153			const d = new Date(document._botmon.t0);
154			const raw = seed + '|' + location.hostname + '|' + extIp + '|' + d.toISOString().substring(0, 10);
155
156			const hash = $BMCaptcha.digest.hash(raw);
157			console.log('Setting cookie to:', raw, ' --> ', hash);
158			document.cookie = "captcha=" + hash + ';';
159
160			window.location.reload(true);
161		}
162	}
163
164}
165// initialise the captcha module:
166$BMCaptcha.init();