Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
747 lines (700 loc) · 36.4 KB
/
Copy pathscript.js
File metadata and controls
747 lines (700 loc) · 36.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
/* Bekha — terminal portfolio. Plain JS, no dependencies. */
(() => {
'use strict';
const REDUCED = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const TZ = 'Asia/Dushanbe';
const THEMES = ['amber', 'green', 'white'];
const BOOT_STEP_MS = 140;
const GH_USER = 'pythonhack000';
const HOME = '/home/bekha';
const I = window.bekhaI18n || { t: (k) => k, set: () => false, lang: 'en' };
const t = (...a) => I.t(...a);
const GLYPHS = '!<>-_\\/[]{}=+*^?#$%&@01';
const LINKS = Object.freeze({
telegram: 'https://t.me/sabr_sf0',
email: 'mailto:pythonhack000@gmail.com',
github: 'https://github.com/pythonhack000',
linkedin: 'https://www.linkedin.com/in/behruz-nabizoda-669491238/',
});
const PROJECTS = Object.freeze([
{ name: 'lunar-navigator', what: 'NASA Space Apps 2026: Moon landing sites', url: 'https://pythonhack000.github.io/lunar-navigator/' },
{ name: 'feudlands', what: 'daily island war inside a Reddit post', url: 'https://www.reddit.com/r/feudlands_dev/comments/1y4sw8n/feudlands_day_1_cats_or_dogs_pick_a_side_and_take/' },
{ name: 'crumple', what: 'daily trick-shot puzzle for Reddit', url: 'https://github.com/pythonhack000/crumple' },
{ name: 'page-100', what: 'teletext news that loads on 2G', url: 'https://pythonhack000.github.io/page-100/' },
{ name: 'spherex-blink', what: 'NASA SPHEREx blink comparator', url: 'https://pythonhack000.github.io/spherex-blink/' },
{ name: 'answering-machine', what: 'call screening with a brain', url: 'https://pythonhack000.github.io/answering-machine/' },
{ name: 'tradeboard', what: 'AI draws on a live trading chart', url: 'https://pythonhack000.github.io/tradevision/' },
{ name: 'store-pos', what: 'desktop till and stock for a shop, Electron', url: null },
{ name: 'smart-canteen', what: 'canteen ordering app, Expo', url: null },
{ name: 'accbozor', what: 'game account marketplace with escrow', url: 'https://pythonhack000.github.io/bozor/' },
{ name: 'bysabr', what: 'fashion store with an admin panel', url: 'https://pythonhack000.github.io/bysabr-shop/' },
{ name: 'takhtabozor', what: 'stock and debts for a timber yard', url: 'https://pythonhack000.github.io/takhtabozor/' },
{ name: 'flex', what: 'one pass for Dushanbe gyms', url: 'https://pythonhack000.github.io/gym/' },
{ name: 'tradesignal-bot', what: 'Telegram signals bot, Python + OpenAI', url: null },
{ name: 'dii-campus', what: 'student app for DII', url: 'https://pythonhack000.github.io/dii-campus/' },
]);
/* ---------------- the name decrypts once ---------------- */
function decrypt(el, durationMs) {
const target = el.dataset.text || el.textContent;
if (REDUCED) { el.textContent = target; return; }
const start = performance.now();
const frame = (now) => {
const p = Math.min(1, (now - start) / durationMs);
const fixed = Math.floor(p * target.length);
el.textContent = target.split('').map((ch, i) =>
i < fixed ? ch : GLYPHS[Math.floor(Math.random() * GLYPHS.length)]
).join('');
if (p < 1) requestAnimationFrame(frame);
else el.textContent = target;
};
requestAnimationFrame(frame);
setTimeout(() => { el.textContent = target; }, durationMs + 400); // rAF can stall in a background tab
}
const firstVisit = !document.documentElement.classList.contains('seen');
try { sessionStorage.setItem('seen', '1'); } catch (e) { /* storage blocked: intro plays every time */ }
const nameEl = document.getElementById('name');
if (nameEl) setTimeout(() => decrypt(nameEl, 1100), firstVisit && !REDUCED ? 650 : 0);
/* ---------------- word to ASCII art (for projects without a screenshot) ---------------- */
function asciiWord(word) {
const cols = 72, rows = 14;
const c = document.createElement('canvas');
c.width = cols; c.height = rows;
const g = c.getContext('2d', { willReadFrequently: true });
if (!g) return word;
g.fillStyle = '#000'; g.fillRect(0, 0, cols, rows);
g.fillStyle = '#fff';
g.textBaseline = 'middle'; g.textAlign = 'center';
let size = rows * 1.15;
g.font = `${size}px VT323, monospace`;
while (g.measureText(word).width > cols - 4 && size > 6) { size -= 1; g.font = `${size}px VT323, monospace`; }
g.fillText(word, cols / 2, rows / 2 + 1);
const data = g.getImageData(0, 0, cols, rows).data;
const RAMP = ' .:-=+*#%@';
let s = '';
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const v = data[(y * cols + x) * 4] / 255;
s += RAMP[Math.min(RAMP.length - 1, Math.floor(v * RAMP.length))];
}
s += '\n';
}
return s;
}
/* ---------------- live checks: one HEAD request per live project ---------------- */
const pingCache = new Map();
const canPing = (url) => Boolean(url) && url.startsWith(location.origin) && location.protocol.startsWith('http');
async function check(url) {
const t0 = performance.now();
try {
const res = await fetch(url, { method: 'HEAD', cache: 'no-store' });
const result = { ok: res.ok, status: res.status, ms: Math.round(performance.now() - t0) };
pingCache.set(url, result);
return result;
} catch (err) {
const result = { ok: false, status: 0, ms: 0 };
pingCache.set(url, result);
return result;
}
}
const describe = (r) => (r.status ? `HTTP ${r.status} ${r.ms}ms` : t('pingNone'));
/* ---------------- nmap rows drive the screen ---------------- */
const rows = Array.from(document.querySelectorAll('.row'));
const crt = document.querySelector('.screen__crt');
const shot = document.getElementById('shot');
const shotAscii = document.getElementById('shotAscii');
const shotCap = document.getElementById('shotCap');
const pingEl = document.getElementById('ping');
const asciiCache = new Map();
const rowUrl = (row) => row.querySelector('a.row__link')?.href ?? null;
const rowName = (row) => row.querySelector('.row__name')?.textContent ?? '';
rows.forEach((r) => { if (r.dataset.shot) { const i = new Image(); i.src = r.dataset.shot; } });
function markRow(row, result) {
const state = row.querySelector('.row__state');
if (!state) return;
state.classList.remove('is-checking');
state.textContent = result.ok ? 'open' : 'down';
state.classList.toggle('is-down', !result.ok);
}
let pingToken = 0;
async function showPing(row) {
if (!pingEl) return;
const token = ++pingToken;
const url = rowUrl(row);
pingEl.className = 'ping';
if (!url) { pingEl.textContent = t('pingPrivate'); return; }
if (url.startsWith('https://github.com/')) { pingEl.textContent = t('pingGithub'); return; }
if (!canPing(url)) { pingEl.textContent = ''; return; }
pingEl.textContent = t('pingWait');
const r = await check(url);
if (token !== pingToken) return;
pingEl.textContent = describe(r);
pingEl.classList.toggle('is-down', !r.ok);
markRow(row, r);
}
function setActive(row) {
if (!row || row.classList.contains('is-on')) return;
rows.forEach((r) => r.classList.toggle('is-on', r === row));
const port = row.querySelector('.row__port')?.textContent ?? '';
const name = rowName(row);
if (shotCap) shotCap.textContent = `${port} ${name}`;
if (row.dataset.shot) {
shotAscii.hidden = true;
shot.hidden = false;
shot.src = row.dataset.shot;
shot.alt = row.dataset.alt || name;
} else {
const key = row.dataset.ascii || name.toUpperCase();
if (!asciiCache.has(key)) asciiCache.set(key, asciiWord(key));
shotAscii.textContent = asciiCache.get(key);
shotAscii.hidden = false;
shot.hidden = true;
}
showPing(row);
document.dispatchEvent(new CustomEvent('bekha:channel', { detail: { port: port.replace('/tcp', ''), name } }));
if (crt && !REDUCED) { crt.classList.remove('is-tuning'); void crt.offsetWidth; crt.classList.add('is-tuning'); }
}
rows.forEach((r) => {
r.addEventListener('pointerenter', () => { if (!r.classList.contains('is-on')) window.bekhaExtras?.sound.hover(rows.indexOf(r)); setActive(r); });
r.addEventListener('focusin', () => setActive(r));
});
if (rows[0]) showPing(rows[0]);
/* nine ports stay folded until asked for, the way nmap says "Not shown" */
const scanEl = document.querySelector('.scan');
const moreBtn = document.getElementById('scanMore');
function setExpanded(open) {
scanEl.classList.toggle('is-all', open);
moreBtn.setAttribute('aria-expanded', String(open));
}
if (scanEl && moreBtn) {
moreBtn.addEventListener('click', () => {
const open = !scanEl.classList.contains('is-all');
setExpanded(open);
if (open) {
rows.find((r) => r.classList.contains('row--more'))?.querySelector('.row__link')?.focus({ preventScroll: true });
return;
}
if (rows.find((r) => r.classList.contains('is-on'))?.classList.contains('row--more')) setActive(rows[0]);
document.getElementById('work')?.scrollIntoView({ behavior: REDUCED ? 'auto' : 'smooth', block: 'start' });
});
}
/* the scan: when /work comes into view, check every live port for real */
const uptime = document.getElementById('uptime');
const uptimeText = document.getElementById('uptimeText');
let scanned = false;
let uptimeState = ['uptimeWait'];
async function scan() {
if (scanned || !uptime) return;
scanned = true;
const live = rows.filter((r) => canPing(rowUrl(r)));
if (!live.length) { uptimeState = ['uptimeLocal']; uptimeText.textContent = t('uptimeLocal'); return; }
live.forEach((r) => r.querySelector('.row__state')?.classList.add('is-checking'));
uptimeText.textContent = t('uptimeRun', live.length);
const results = await Promise.all(live.map(async (r) => { const res = await check(rowUrl(r)); markRow(r, res); window.bekhaExtras?.sound.ping(res.ok, rows.indexOf(r)); return res; }));
const up = results.filter((r) => r.ok);
const sorted = up.map((r) => r.ms).sort((a, b) => a - b);
const median = sorted.length ? sorted[Math.floor(sorted.length / 2)] : 0;
uptimeState = ['uptimeDone', up.length, results.length, median];
uptimeText.textContent = t(...uptimeState);
uptime.classList.add(up.length === results.length ? 'is-done' : 'is-bad');
}
if (uptime) {
new IntersectionObserver(([e], obs) => { if (e.isIntersecting) { scan(); obs.disconnect(); } }, { rootMargin: '0px 0px -30% 0px' }).observe(uptime);
}
/* ---------------- live GitHub in neofetch ---------------- */
function ago(iso) {
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
const units = [['year', 31536000], ['month', 2592000], ['day', 86400], ['hour', 3600], ['minute', 60]];
for (const [u, sec] of units) { const n = Math.floor(s / sec); if (n >= 1) return t('ago', n, u); }
return t('ago', 0, 'now');
}
const ghFill = (id, text) => { const el = document.getElementById(id); if (!el) return; el.querySelector('dd').textContent = text; el.hidden = false; };
const github = { repos: null, last: null };
function paintGithub() {
if (github.repos !== null) ghFill('ghRepos', t('ghRepos', github.repos));
if (github.last) ghFill('ghPush', t('ghPush', ago(github.last.at), github.last.name));
}
/* one cached copy for every visitor from our server (gh function); GitHub directly only if that is down.
gitlog.js reads the same promise for `git log`. */
const getJson = (url) => fetch(url).then((r) => (r.ok ? r.json() : Promise.reject(new Error(`${url} ${r.status}`))));
async function githubDirect() {
const [user, repos] = await Promise.all([
getJson(`https://api.github.com/users/${GH_USER}`),
getJson(`https://api.github.com/users/${GH_USER}/repos?sort=pushed&per_page=1`),
]);
const top = Array.isArray(repos) ? repos[0] : null;
return { repos: typeof user.public_repos === 'number' ? user.public_repos : null, last: top?.pushed_at ? { name: top.name, at: top.pushed_at } : null, commits: null };
}
const API = window.BEKHA_CONFIG?.api || '';
window.bekhaGithub = (API ? getJson(`${API}/gh`).then((j) => (j.success ? j.data : Promise.reject(new Error(j.error)))) : Promise.reject(new Error('no api')))
.catch(() => githubDirect());
window.bekhaGithub.then((d) => {
github.repos = d.repos;
github.last = d.last;
paintGithub();
}).catch(() => { /* GitHub rate limit or offline: the rows stay hidden, nothing else depends on them */ });
/* ---------------- the terminal: a small shell over the page ---------------- */
const term = document.getElementById('term');
const out = document.getElementById('termOut');
const form = document.getElementById('termForm');
const input = document.getElementById('termIn');
const psEl = document.getElementById('termPs');
const titleEl = document.getElementById('termTitle');
const respawn = document.getElementById('termRespawn');
const history = [];
let histIdx = 0;
let cwd = '~';
const DIRS = Object.freeze({ '~': 'top', '~/work': 'work', '~/whoami': 'whoami', '~/contact': 'contact' });
const FILES = Object.freeze(['security.log', 'nasa.txt']);
const print = (text, cls) => {
const p = document.createElement('p');
if (cls) p.className = cls;
p.textContent = text;
out.appendChild(p);
out.scrollTop = out.scrollHeight;
};
const go = (url) => { if (url) window.open(url, url.startsWith('mailto:') ? '_self' : '_blank', 'noopener'); };
/* extension points for ctf.js, ssh.js, gitlog.js and resume: commands, files, sudo rules, input capture */
const ext = { commands: new Map(), files: new Map(), sudo: [], help: [], capture: null };
window.bekhaShell = Object.freeze({
print,
go,
input,
/* fx.js types into the shell as if someone were at the keyboard (run() echoes the line itself) */
run: (line) => { if (input && !term.classList.contains('is-closed')) run(line); },
ago: (iso) => ago(iso),
/** @param {string} name @param {(args: string[], raw: string) => void} fn @param {string} [help] */
command(name, fn, help) { ext.commands.set(name, fn); if (help) ext.help.push([` ${help}`]); },
/** @param {string} path full path as typed, e.g. /root/flag.txt @param {() => Array<[string, string?]>} read */
file(path, read) { ext.files.set(path, read); },
/** @param {(args: string[]) => boolean} rule returns true when it handled the sudo line */
sudo(rule) { ext.sudo.push(rule); },
/** route the next lines to fn instead of the shell (ssh message entry); null hands control back */
capture(fn, prompt) { ext.capture = fn; if (psEl) psEl.textContent = fn ? (prompt || '>') : `bekha@dushanbe:${cwd}$`; },
});
const jump = (id) => document.getElementById(id)?.scrollIntoView({ behavior: REDUCED ? 'auto' : 'smooth' });
const setCwd = (dir) => {
cwd = dir;
if (psEl) psEl.textContent = `bekha@dushanbe:${dir}$`;
if (titleEl) titleEl.textContent = `tty1 bekha@dushanbe:${dir}`;
};
const findProject = (q) => PROJECTS.find((p) => p.name.startsWith(q || '\u0000'));
const rowFor = (name) => rows.find((r) => rowName(r) === name);
function catProject(p) {
const row = rowFor(p.name);
const lines = [[p.name, 'hl']];
const ver = row?.querySelector('.row__ver')?.textContent?.trim();
if (ver) lines.push([ver]);
lines.push([p.url ? `url ${p.url}` : 'url private, on a VPS']);
const r = p.url ? pingCache.get(p.url) : null;
if (r) lines.push([`status ${describe(r)}`]);
return lines;
}
const COMMANDS = {
help: () => [
['the site is a filesystem. commands:', 'hl'],
[' ls [dir] list a directory (work, whoami, contact)'],
[' cd <dir> go there, the page follows'],
[' cat <file> read a project or a file, e.g. cat tradeboard'],
[' run <name> boot a live project in a BEKHA-OS window'],
[' open <name> open a live project in a new tab'],
[' pwd, tree, whoami, stack, nasa, contact'],
[' telegram | email | github | linkedin'],
[' theme <name> amber, green or white'],
[' lang en|ru English or Russian'],
[' reboot power-cycle the screen'],
[' intro replay the opening shot'],
[' whereami where you are, and how far from me'],
[' snake play. arrows or WASD'],
[' hack do not'],
[' sound on|off interface sound'],
[' sound pack <n> retro, cyber or cinema'],
[' sudo hire-me you know what this does'],
...ext.help,
[' clear, exit'],
],
whoami: () => {
const lines = [[t('whoami1')], [t('whoami2')]];
if (github.last) lines.push([t('lastPush', ago(github.last.at), github.last.name), 'echo']);
return lines;
},
pwd: () => [[cwd === '~' ? HOME : HOME + cwd.slice(1)]],
tree: () => [['~'], ['|-- work/'], ...PROJECTS.map((p, i) => [`| ${i === PROJECTS.length - 1 ? '`--' : '|--'} ${p.name}`]), ['|-- whoami/'], ['|-- contact/'], ['|-- security.log'], ['`-- nasa.txt'], [`3 directories, ${PROJECTS.length + 2} files`, 'echo']],
projects: () => PROJECTS.map((p) => [` ${p.name.padEnd(18)}${p.what}`]).concat([['try: cat tradeboard, or open lunar', 'echo']]),
stack: () => [['TypeScript, React, Next.js, Vite, Tailwind'], ['Supabase, PostgreSQL, Flask'], ['Expo, React Native, Flutter'], ['Python, OpenAI, Anthropic, Gemini, Telegram Bot API']],
contact: () => [['telegram @sabr_sf0'], ['email pythonhack000@gmail.com'], ['github pythonhack000'], ['type a name to open it, e.g. telegram', 'echo']],
telegram: () => { go(LINKS.telegram); return [['opening telegram...']]; },
email: () => { go(LINKS.email); return [['opening mail...']]; },
github: () => { go(LINKS.github); return [['opening github...']]; },
linkedin: () => { go(LINKS.linkedin); return [['opening linkedin...']]; },
date: () => [[new Date().toLocaleString('en-GB', { timeZone: TZ, dateStyle: 'full', timeStyle: 'short' }) + ' in Dushanbe']],
nasa: () => [[t('nasa1'), 'hl'], [t('nasa2')], [t('nasa3'), 'echo']],
exit: () => { setTimeout(closeShell, 250); return [['logout']]; },
reboot: () => { setTimeout(reboot, 300); return [['the system is going down for reboot NOW']]; },
whereami: () => {
const v = window.bekhaGlobe?.visitor?.();
if (!v) return [['whereami: no globe loaded', 'err']];
const ru = I.lang === 'ru';
if (v.km <= 150) return [[ru ? `ты в ${v.ru}. мы соседи. заходи на чай.` : `you are in ${v.en}. we are neighbours. come over.`, 'hl']];
return [
[ru ? `ты где-то тут: ${v.ru} (${v.tz || 'часовой пояс неизвестен'})` : `you are around ${v.en} (${v.tz || 'unknown time zone'})`, 'hl'],
[ru ? `${v.km} км до Душанбе. посмотри на глобус: туда бежит пакет.` : `${v.km} km to Dushanbe. look at the globe: a packet is on its way.`],
[ru ? 'это по часовому поясу браузера, ни IP, ни геолокации.' : 'guessed from your browser time zone. no IP, no geolocation.', 'echo'],
];
},
intro: () => { try { sessionStorage.removeItem('intro'); } catch (e) { /* plays anyway after reload */ } setTimeout(() => location.reload(), 300); return [['replaying the opening shot...']]; },
clear: () => { out.textContent = ''; return []; },
};
function ls(arg) {
const target = arg ? (arg.startsWith('~') ? arg : (cwd === '~' ? `~/${arg}` : `${cwd}/${arg}`)).replace(/\/$/, '') : cwd;
if (target === '~') return [['work/ whoami/ contact/ security.log nasa.txt']];
if (target === '~/work') return COMMANDS.projects();
if (target === '~/whoami') return [['neofetch security.log']];
if (target === '~/contact') return [['telegram email github linkedin']];
return [[`ls: cannot access '${arg}': no such directory`, 'err']];
}
function cd(arg) {
if (!arg || arg === '~' || arg === '/' || arg === HOME) { setCwd('~'); jump('top'); return []; }
if (arg === '..') { setCwd('~'); jump('top'); return []; }
const clean = arg.replace(/\/$/, '').replace(/^~\//, '').replace(/^\.\//, '');
const dir = `~/${clean}`;
if (DIRS[dir]) { setCwd(dir); jump(DIRS[dir]); return []; }
if (findProject(clean)) return [[`cd: ${clean}: is a project, not a directory. try cat ${clean} or open ${clean}`, 'err']];
return [[`cd: no such directory: ${arg}`, 'err']];
}
function cat(arg) {
if (!arg) return [['cat: what? e.g. cat tradeboard', 'err']];
if (ext.files.has(arg)) return ext.files.get(arg)();
const clean = arg.replace(/^.*\//, '');
if (clean === 'security.log') return Array.from(document.querySelectorAll('.log li')).map((li) => [li.textContent.trim()]);
if (clean === 'nasa.txt') return COMMANDS.nasa();
const p = findProject(clean);
if (p) return catProject(p);
if (DIRS[`~/${clean}`]) return [[`cat: ${clean}: is a directory`, 'err']];
return [[`cat: ${clean}: no such file`, 'err']];
}
function run(raw) {
if (ext.capture) { print(`> ${raw}`, 'echo'); ext.capture(raw); return; }
const line = raw.trim();
if (!line) return;
print(`${cwd}$ ${line}`, 'echo');
setTimeout(() => window.bekhaExtras?.sound.data(110), 70);
const [cmd, ...args] = line.toLowerCase().split(/\s+/);
const say = (lines) => lines.forEach(([text, cls]) => print(text, cls));
if (ext.commands.has(cmd)) { ext.commands.get(cmd)(line.split(/\s+/).slice(1), line); return; }
if (cmd === 'sudo') {
if (args.join(' ') === 'hire-me' || args.join(' ') === 'hire me') {
print('[sudo] password for visitor: ********');
print('access granted. opening a chat with Bekha...', 'hl');
go(LINKS.telegram);
} else if (!ext.sudo.some((rule) => rule(args))) {
print('visitor is not in the sudoers file. This incident will be reported.', 'err');
}
return;
}
if (cmd === 'theme') {
const name = args[0];
if (!THEMES.includes(name)) { print(`themes: ${THEMES.join(', ')}. e.g. theme green`, 'err'); return; }
if (name === 'amber') delete document.documentElement.dataset.theme;
else document.documentElement.dataset.theme = name;
try { localStorage.setItem('theme', name === 'amber' ? '' : name); } catch (e) { /* not saved, still applied */ }
print(`phosphor set to ${name}.`, 'hl');
return;
}
if (cmd === 'lang') {
if (!I.set(args[0])) { print('lang: en or ru', 'err'); return; }
print(t('langSet'), 'hl');
return;
}
if (cmd === 'rm') { print('nice try.', 'err'); return; }
const X = window.bekhaExtras;
if (cmd === 'snake') {
if (!X) { print('snake is not installed.', 'err'); return; }
if (window.matchMedia('(hover: none)').matches) { print('snake needs a keyboard. try it on a laptop.', 'err'); return; }
X.snake({ out, input, print, setWin });
return;
}
if (cmd === 'hack') { if (X) X.breach(); return; }
if (cmd === 'sound') {
if (!X) { print('no sound card.', 'err'); return; }
if (args[0] === 'pack') {
const name = args[1];
if (!name) { print(`sound packs: ${X.sound.packs.join(', ')}. current: ${X.sound.pack}.`); return; }
if (!X.sound.setPack(name)) { print(`no pack "${name}". try: ${X.sound.packs.join(', ')}.`, 'err'); return; }
if (!X.sound.on) X.sound.set(true); else X.sound.thunk();
print(`sound pack: ${name}.`, 'hl');
return;
}
const want = args[0] === 'off' ? false : args[0] === 'on' ? true : !X.sound.on;
X.sound.set(want);
print(`sound ${want ? `on, pack ${X.sound.pack}` : 'off'}.`, 'hl');
return;
}
if (cmd === 'ls') { say(ls(args[0])); return; }
if (cmd === 'cd') { say(cd(args[0])); return; }
if (cmd === 'cat' || cmd === 'less' || cmd === 'more') { say(cat(args[0])); return; }
if (cmd === 'run') {
if (!window.bekhaOS || !window.bekhaOS.run(args[0] || '\u0000')) { print(`run: ${args[0] || ''}: no live project by that name. type ls work`, 'err'); return; }
print(`booting ${args[0]}...`, 'hl');
return;
}
if (cmd === 'open') {
const target = findProject(args[0]);
if (!target) { print(`no such project: ${args[0] || ''}. type ls work`, 'err'); return; }
if (!target.url) { print(`${target.name} runs privately on a VPS. Ask me for a demo: type telegram`); return; }
print(`opening ${target.name}...`, 'hl');
go(target.url);
return;
}
const fn = Object.prototype.hasOwnProperty.call(COMMANDS, cmd) ? COMMANDS[cmd] : null;
if (!fn) { print(`command not found: ${cmd}. type help`, 'err'); return; }
say(fn());
}
/* boot log, also used by reboot */
const READY = () => t('ready');
function boot(animated) {
if (!out) return;
if (!animated) { print(READY(), 'hl'); return; }
const lines = ['[ ok ] phosphor warm', `[ ok ] mounted /work: ${PROJECTS.length} projects`, '[ ok ] loaded neofetch, security.log', READY()];
lines.forEach((line, i) => setTimeout(() => {
print(line, i === lines.length - 1 ? 'hl' : 'echo');
window.bekhaExtras?.sound.data(i === lines.length - 1 ? 260 : 90);
}, 900 + i * BOOT_STEP_MS));
}
function reboot() {
window.bekhaExtras?.sound.thunk();
window.scrollTo({ top: 0, behavior: 'auto' });
const old = document.querySelector('.power');
if (old && !REDUCED) {
const fresh = old.cloneNode(true);
old.replaceWith(fresh);
}
document.documentElement.classList.remove('seen');
openShell();
out.textContent = '';
setCwd('~');
if (nameEl) setTimeout(() => decrypt(nameEl, 1100), REDUCED ? 0 : 650);
boot(!REDUCED);
}
/* window controls */
function setWin(state) {
term.classList.remove('is-min', 'is-max', 'is-closed');
if (state) term.classList.add(`is-${state}`);
term.querySelector('[data-win="min"]')?.setAttribute('aria-pressed', String(state === 'min'));
term.querySelector('[data-win="max"]')?.setAttribute('aria-pressed', String(state === 'max'));
respawn.hidden = state !== 'closed';
document.body.style.overflow = state === 'max' ? 'hidden' : '';
}
function closeShell() { setWin('closed'); respawn.focus(); }
function openShell() { setWin(null); }
if (term && out && form && input && respawn) {
boot(firstVisit && !REDUCED);
term.querySelectorAll('[data-win]').forEach((btn) => btn.addEventListener('click', () => {
const want = btn.dataset.win;
if (want === 'close') { closeShell(); return; }
const on = term.classList.contains(`is-${want}`);
setWin(on ? null : want);
if (!on && want === 'max') input.focus();
}));
respawn.addEventListener('click', () => {
openShell();
out.textContent = '';
setCwd('~');
print('respawned. bash 5.2, a fresh shell.', 'hl');
input.focus();
});
form.addEventListener('submit', (e) => {
e.preventDefault();
const v = input.value;
if (v.trim() && !ext.capture) { history.push(v); histIdx = history.length; }
input.value = '';
run(v);
});
const WORDS = Object.keys(COMMANDS).concat(['ls', 'cd', 'cat', 'open', 'run', 'sudo hire-me', 'theme', 'snake', 'hack', 'sound on', 'sound off', 'sound pack cyber', 'sound pack cinema', 'sound pack retro', 'lang en', 'lang ru']);
/* candidates for what is typed so far: Tab cycles through them, the grey suggestion shows the best one */
function completions(v) {
const [cmd] = v.split(/\s+/);
let pool = ['chat', 'ssh bekha', 'git log', 'ctf join', 'ctf top', 'resume --pdf'].concat(WORDS, [...ext.commands.keys()]);
if (cmd === 'open' || cmd === 'run') pool = PROJECTS.map((p) => `${cmd} ${p.name}`);
if (cmd === 'cat') pool = PROJECTS.map((p) => `cat ${p.name}`).concat(FILES.map((f) => `cat ${f}`), ['cat resume']);
if (cmd === 'cd' || cmd === 'ls') pool = ['work', 'whoami', 'contact'].map((d) => `${cmd} ${d}`);
if (cmd === 'theme') pool = THEMES.map((th) => `theme ${th}`);
return [...new Set(pool)].filter((w) => w.startsWith(v));
}
const suggestEl = document.getElementById('termSuggest');
let suggestion = '';
function showSuggestion() {
const v = input.value;
suggestion = '';
if (v.trim() && !ext.capture && input.selectionStart === v.length) {
const low = v.toLowerCase();
const past = [...history].reverse().find((h) => h.toLowerCase().startsWith(low) && h.length > v.length);
const hit = past || completions(low).find((w) => w.length > v.length);
if (hit) suggestion = v + hit.slice(v.length);
}
if (!suggestEl) return;
const fits = input.scrollWidth <= input.clientWidth;
suggestEl.firstChild.textContent = suggestion && fits ? v : '';
suggestEl.lastChild.textContent = suggestion && fits ? suggestion.slice(v.length) : '';
}
input.addEventListener('input', showSuggestion);
input.addEventListener('blur', () => { suggestion = ''; if (suggestEl) { suggestEl.firstChild.textContent = ''; suggestEl.lastChild.textContent = ''; } });
form.addEventListener('submit', () => setTimeout(showSuggestion, 0));
input.addEventListener('keydown', (e) => {
if (e.key.length === 1 || e.key === 'Backspace' || e.key === 'Enter') {
window.bekhaExtras?.sound.key(e.key === 'Enter' ? 'enter' : e.key === ' ' ? 'space' : 'char');
}
const atEnd = input.selectionStart === input.value.length;
if (suggestion && atEnd && (e.key === 'ArrowRight' || e.key === 'End' || e.key === 'Tab')) {
input.value = suggestion;
showSuggestion();
e.preventDefault();
return;
}
if (e.key === 'Tab' && input.value.trim()) {
const hits = completions(input.value.toLowerCase().trim());
if (hits.length === 1) input.value = hits[0] + ' ';
else if (hits.length > 1) print(hits.join(' '), 'echo');
showSuggestion();
e.preventDefault();
return;
}
if (e.key === 'ArrowUp' && histIdx > 0) { histIdx -= 1; input.value = history[histIdx]; e.preventDefault(); showSuggestion(); }
if (e.key === 'ArrowDown') { histIdx = Math.min(history.length, histIdx + 1); input.value = history[histIdx] ?? ''; e.preventDefault(); showSuggestion(); }
if (e.key === 'l' && e.ctrlKey) { out.textContent = ''; e.preventDefault(); }
if (e.key === 'c' && e.ctrlKey && ext.capture) { e.preventDefault(); input.value = ''; ext.capture('\u0003'); }
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && term.classList.contains('is-max')) { setWin(null); return; }
const typing = /^(INPUT|TEXTAREA)$/.test(document.activeElement?.tagName ?? '');
if (e.key === '/' && !typing) {
e.preventDefault();
if (term.classList.contains('is-closed') || term.classList.contains('is-min')) openShell();
input.focus();
}
});
}
/* ---------------- effects you see without typing ---------------- */
/* the background is this page's own running code, lit where the pointer goes */
const srcDim = document.getElementById('srcDim');
const srcLit = document.getElementById('srcLit');
if (srcDim && srcLit) {
const own = [decrypt, window.bekhaGlobe?.frame, asciiWord, check, showPing, scan, run, ls, cd, cat, boot, reboot, setWin]
.filter(Boolean).map((fn) => fn.toString()).join('\n\n');
const need = Math.ceil(window.innerHeight / 17.4) * Math.ceil(window.innerWidth / 460) * 60 + 2000;
let text = own;
while (text.length < need) text += '\n\n' + own;
srcDim.textContent = text;
srcLit.textContent = text;
if (!REDUCED && window.matchMedia('(hover: hover)').matches) {
const root = document.documentElement;
let mx = -999, my = -999, queued = false;
const paint = () => { root.style.setProperty('--mx', `${mx}px`); root.style.setProperty('--my', `${my}px`); queued = false; };
window.addEventListener('pointermove', (e) => {
mx = e.clientX; my = e.clientY;
root.style.setProperty('--lamp', '190px');
if (!queued) { queued = true; requestAnimationFrame(paint); }
}, { passive: true });
document.addEventListener('pointerleave', () => root.style.setProperty('--lamp', '0px'));
}
}
/* headings decrypt once, as they scroll into view */
if (!REDUCED) {
const heads = Array.from(document.querySelectorAll('.h2, .h3, .contact__h'));
heads.forEach((el) => { el.dataset.text = el.textContent; });
const io = new IntersectionObserver((entries) => {
entries.forEach((e) => { if (e.isIntersecting) { decrypt(e.target, 900); io.unobserve(e.target); } });
}, { rootMargin: '0px 0px -15% 0px' });
heads.forEach((el) => io.observe(el));
}
/* the name and the contact labels re-scramble under the pointer */
const hoverScramble = (el, ms) => {
let busy = false;
el.addEventListener('pointerenter', () => {
if (busy || REDUCED) return;
busy = true;
decrypt(el, ms);
setTimeout(() => { busy = false; }, ms + 450);
});
};
document.querySelectorAll('.big').forEach((a) => {
const label = a.querySelector('.big__label');
if (!label) return;
let busy = false;
a.addEventListener('pointerenter', () => { if (busy || REDUCED) return; busy = true; decrypt(label, 450); setTimeout(() => { busy = false; }, 900); });
});
/* the sound switch in the top bar */
const soundBtn = document.getElementById('soundBtn');
if (soundBtn && window.bekhaExtras) {
const label = (on) => { soundBtn.textContent = t(on ? 'soundOn' : 'soundOff'); soundBtn.setAttribute('aria-pressed', String(on)); };
document.addEventListener('bekha:lang', () => label(window.bekhaExtras.sound.on));
label(window.bekhaExtras.sound.on);
soundBtn.addEventListener('click', () => window.bekhaExtras.sound.set(!window.bekhaExtras.sound.on));
document.addEventListener('bekha:sound', (e) => label(e.detail));
}
/* scroll progress, drawn as a terminal progress bar */
const prog = document.getElementById('prog');
if (prog) {
const CELLS = 20;
let queued = false;
const draw = () => {
const max = document.documentElement.scrollHeight - window.innerHeight;
const p = max > 0 ? Math.min(1, Math.max(0, window.scrollY / max)) : 0;
const full = Math.round(p * CELLS);
prog.textContent = `[${'#'.repeat(full)}${'-'.repeat(CELLS - full)}] ${String(Math.round(p * 100)).padStart(3, ' ')}%`;
queued = false;
};
window.addEventListener('scroll', () => { if (!queued) { queued = true; requestAnimationFrame(draw); } }, { passive: true });
draw();
}
/* a language switch repaints what the scripts wrote */
document.addEventListener('bekha:lang', () => {
if (uptimeText) uptimeText.textContent = t(...uptimeState);
paintGithub();
const on = rows.find((r) => r.classList.contains('is-on'));
if (on) showPing(on);
});
/* ---------------- scroll: each section prints itself as it comes into view ---------------- */
if (!REDUCED && 'IntersectionObserver' in window) {
document.documentElement.classList.add('rv-on');
const groups = [
['#work', '.scan__head, .row, .done, .uptime'],
['.neo', '.neo__list > div, .neo__user, .neo__swatch, .neo__cap'],
['.sec', '.h3, .log li'],
['#contact', '.contact__lead, .links li'],
];
groups.forEach(([host, sel]) => {
const root = document.querySelector(host);
if (!root) return;
root.querySelectorAll(sel).forEach((el, i) => { el.classList.add('rv'); el.style.setProperty('--i', String(i)); });
});
/* the command line above each section types itself, once */
const typeOut = (el) => {
const ps = el.querySelector('.prompt__ps');
const text = el.textContent.replace(ps ? ps.textContent : '', '').trim();
el.textContent = '';
if (ps) el.append(ps, ' ');
const span = document.createElement('span');
el.appendChild(span);
el.classList.add('is-typing');
let i = 0;
const step = () => {
span.textContent = text.slice(0, ++i);
if (i < text.length) setTimeout(step, 28 + Math.random() * 40);
else setTimeout(() => el.classList.remove('is-typing'), 500);
};
step();
};
const watch = new IntersectionObserver((entries) => {
entries.forEach((e) => {
if (!e.isIntersecting) return;
const el = e.target;
el.classList.add('in');
if (el.classList.contains('cmd')) typeOut(el);
watch.unobserve(el);
});
}, { rootMargin: '0px 0px -18% 0px', threshold: 0.05 });
document.querySelectorAll('#work, .neo, .sec, #contact, main .cmd').forEach((el) => watch.observe(el));
}
/* after the opening shot the name decrypts once more, in front of the visitor */
document.addEventListener('bekha:intro-done', () => { if (nameEl) decrypt(nameEl, 900); });
})();