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