xref: /plugin/botmon/captcha.js (revision 447b8b4fbe99d4a8eee9e007372c2b4dde8fc42f)
1"use strict";
2/* DokuWiki BotMon Captcha JavaScript */
3/* 23.10.2025 - 0.1.2 - 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
17		// localisation helper function:
18		let _loc = function(id, alt) {
19			if ($BMLocales && $BMLocales[id]) return $BMLocales[id];
20			return alt;
21		}
22
23		// find the parent element:
24		let bm_parent = document.getElementsByTagName('body')[0];
25
26		// create the dialog:
27		const dlg = document.createElement('dialog');
28		dlg.setAttribute('closedby', 'none');
29		dlg.setAttribute('open', 'open');
30		dlg.classList.add('checking');
31		dlg.id = 'botmon_captcha_box';
32		dlg.innerHTML = '<h2>' + _loc('dlgTitle', 'Title') + '</h2><p>' + _loc('dlgSubtitle', 'Subtitle') + '</p>';
33
34		// Checkbox:
35		const lbl = document.createElement('label');
36		lbl.innerHTML = '<span class="confirm">' + _loc('dlgConfirm', "Confirm.") + '</span>' +
37			'<span class="busy"></span><span class="checking">' + _loc('dlgChecking', "Checking") + '</span>' +
38			'<span class="loading">' + _loc('dlgLoading', "Loading") + '</span>' +
39			'<span class="erricon">&#65533;</span><span class="error">' + _loc('dlgError', "Error") + '</span>';
40		const cb = document.createElement('input');
41		cb.setAttribute('type', 'checkbox');
42		cb.setAttribute('disabled', 'disabled');
43		cb.addEventListener('click', $BMCaptcha._cbCallback);
44		lbl.prepend(cb);
45
46		dlg.appendChild(lbl);
47
48		bm_parent.appendChild(dlg);
49
50		// call the delayed callback in a couple of seconds:
51		setTimeout($BMCaptcha._delayedCallback, 1500);
52	},
53
54	/* creates a digest hash for the cookie function */
55	digest: {
56
57		/* simple SHA hash function - adapted from https://geraintluff.github.io/sha256/ */
58		hash: function(ascii) {
59
60			// shortcut:
61			const sha256 = $BMCaptcha.digest.hash;
62
63			// helper function
64			const rightRotate = function(v, a) {
65				return (v>>>a) | (v<<(32 - a));
66			};
67
68			var mathPow = Math.pow;
69			var maxWord = mathPow(2, 32);
70			var lengthProperty = 'length'
71			var i, j;
72			var result = ''
73
74			var words = [];
75			var asciiBitLength = ascii[lengthProperty]*8;
76
77			//* caching results is optional - remove/add slash from front of this line to toggle
78			// Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
79			// (we actually calculate the first 64, but extra values are just ignored)
80			var hash = sha256.h = sha256.h || [];
81			// Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
82			var k = sha256.k = sha256.k || [];
83			var primeCounter = k[lengthProperty];
84			/*/
85			var hash = [], k = [];
86			var primeCounter = 0;
87			//*/
88
89			var isComposite = {};
90			for (var candidate = 2; primeCounter < 64; candidate++) {
91				if (!isComposite[candidate]) {
92					for (i = 0; i < 313; i += candidate) {
93						isComposite[i] = candidate;
94					}
95					hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
96					k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
97				}
98			}
99
100			ascii += '\x80' // Append Ƈ' bit (plus zero padding)
101			while (ascii[lengthProperty]%64 - 56) ascii += '\x00' // More zero padding
102			for (i = 0; i < ascii[lengthProperty]; i++) {
103				j = ascii.charCodeAt(i);
104				if (j>>8) return; // ASCII check: only accept characters in range 0-255
105				words[i>>2] |= j << ((3 - i)%4)*8;
106			}
107			words[words[lengthProperty]] = ((asciiBitLength/maxWord)|0);
108			words[words[lengthProperty]] = (asciiBitLength)
109
110			// process each chunk
111			for (j = 0; j < words[lengthProperty];) {
112				var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
113				var oldHash = hash;
114				// This is now the undefinedworking hash", often labelled as variables a...g
115				// (we have to truncate as well, otherwise extra entries at the end accumulate
116				hash = hash.slice(0, 8);
117
118				for (i = 0; i < 64; i++) {
119					var i2 = i + j;
120					// Expand the message into 64 words
121					// Used below if
122					var w15 = w[i - 15], w2 = w[i - 2];
123
124					// Iterate
125					var a = hash[0], e = hash[4];
126					var temp1 = hash[7]
127						+ (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
128						+ ((e&hash[5])^((~e)&hash[6])) // ch
129						+ k[i]
130						// Expand the message schedule if needed
131						+ (w[i] = (i < 16) ? w[i] : (
132								w[i - 16]
133								+ (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15>>>3)) // s0
134								+ w[i - 7]
135								+ (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2>>>10)) // s1
136							)|0
137						);
138					// This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
139					var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
140						+ ((a&hash[1])^(a&hash[2])^(hash[1]&hash[2])); // maj
141
142					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()
143					hash[4] = (hash[4] + temp1)|0;
144				}
145
146				for (i = 0; i < 8; i++) {
147					hash[i] = (hash[i] + oldHash[i])|0;
148				}
149			}
150
151			for (i = 0; i < 8; i++) {
152				for (j = 3; j + 1; j--) {
153					var b = (hash[i]>>(j*8))&255;
154					result += ((b < 16) ? 0 : '') + b.toString(16);
155				}
156			}
157			return result;
158		}
159	},
160
161	_cbCallback: function(e) {
162		if (e.target.checked) {
163			//document.getElementById('botmon_captcha_box').close();
164
165			try {
166				var $status = 'loading';
167
168				// generate the hash:
169				const dat = [ // the data to encode
170					document._botmon.seed || '',
171					location.hostname,
172					document._botmon.ip || '0.0.0.0',
173					(new Date()).toISOString().substring(0, 10)
174				];
175				const hash = $BMCaptcha.digest.hash(dat.join('|'));
176
177				// set the cookie:
178				document.cookie = "DWConfirm=" + hash + ';path=/;';
179
180			} catch (err) {
181				console.error(err);
182				$status = 'error';
183			}
184
185			// change the interface:
186			const dlg = document.getElementById('botmon_captcha_box');
187			if (dlg) {
188				dlg.classList.remove('ready');
189				dlg.classList.add( $status );
190			}
191
192			// reload the page:
193			if ($status !== 'error')window.location.reload(true);
194		}
195	},
196
197	_delayedCallback: function() {
198		const dlg = document.getElementById('botmon_captcha_box');
199		if (dlg) {
200			dlg.classList.remove('checking');
201			dlg.classList.add('ready');
202
203			const input = dlg.getElementsByTagName('input')[0];
204			if (input) {
205				input.removeAttribute('disabled');
206				input.focus();
207			}
208		}
209	},
210
211}
212// initialise the captcha module:
213$BMCaptcha.init();