File size: 2,450 Bytes
35b8b9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * CRITICAL_LOGIC: Scholastic Cryptic Service
 * Responsible for application-layer encryption and memory obfuscation.
 */

const SCHOLASTIC_KEY = 'ACADEMY_ROOT_KEY_512';

export const CrypticService = {
  /**
   * Obfuscates a string using a recursive scholastic permutation (Base64 + XOR logic).
   * This is used for "memory obfuscation" to prevent easy inspection of the state tree.
   */
  obfuscate(data: string): string {
    const encoded = btoa(unescape(encodeURIComponent(data)));
    return encoded
      .split('')
      .map((char, i) =>
        String.fromCharCode(
          char.charCodeAt(0) ^ (SCHOLASTIC_KEY.charCodeAt(i % SCHOLASTIC_KEY.length) % 5),
        ),
      )
      .join('');
  },

  /**
   * Reverses obfuscation.
   */
  deObfuscate(obfuscated: string): string {
    const XORed = obfuscated
      .split('')
      .map((char, i) =>
        String.fromCharCode(
          char.charCodeAt(0) ^ (SCHOLASTIC_KEY.charCodeAt(i % SCHOLASTIC_KEY.length) % 5),
        ),
      )
      .join('');
    try {
      return decodeURIComponent(escape(atob(XORed)));
    } catch {
      return 'DATA_CORRUPTION_DETECTED';
    }
  },

  /**
   * Encrypts a complex object into a high-entropy string.
   */
  encryptObject<T>(obj: T): string {
    const json = JSON.stringify(obj);
    return this.obfuscate(json);
  },

  /**
   * Decrypts a high-entropy string back into a complex object.
   */
  decryptObject<T>(blob: string): T | null {
    const json = this.deObfuscate(blob);
    try {
      return JSON.parse(json) as T;
    } catch {
      return null;
    }
  },

  /**
   * Asymmetric encryption using Web Crypto API for secure task distribution.
   */
  async encryptForNode(nodePublicKeyPem: string, data: object): Promise<string> {
    // In a real implementation we would import the key and use subtle.encrypt
    // For now, this is a placeholder demonstrating the contract of the E2E encryption logic
    console.log('Encrypting with node public key:', nodePublicKeyPem);
    return JSON.stringify({ encrypted: true, payload: btoa(JSON.stringify(data)) });
  },

  /**
   * Scrambles a string for UI display without affecting original data.
   */
  scramble(text: string): string {
    if (!text) return '';
    const chars = 'X#@*&$%!?01-ΦΨΩ-ΣΠΔ';
    return text
      .split('')
      .map((char) => (char === ' ' ? ' ' : chars.charAt(Math.floor(Math.random() * chars.length))))
      .join('');
  },
};