fileUtils.ts 952 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. // Compute multiplicative inverse (could use extended Euclidean algorithm)
  2. const PRIME = 1000003; // a large prime > max agentId
  3. const MULTIPLIER = 345679; // secret, coprime with PRIME
  4. const modInverse = (a: number, m: number) => {
  5. let m0 = m, x0 = 0, x1 = 1;
  6. if (m === 1) return 0;
  7. while (a > 1) {
  8. const q = Math.floor(a / m);
  9. [a, m] = [m, a % m];
  10. [x0, x1] = [x1 - q * x0, x0];
  11. }
  12. return x1 < 0 ? x1 + m0 : x1;
  13. };
  14. const MULTIPLIER_INV = modInverse(MULTIPLIER, PRIME);
  15. /**
  16. * Encode agentId to obfuscated base36 string
  17. */
  18. export function encodeAgentId(agentId: number): string {
  19. const scrambled = (agentId * MULTIPLIER) % PRIME;
  20. return scrambled.toString(36).padStart(6, '0');
  21. }
  22. /**
  23. * Decode obfuscated base36 string back to agentId
  24. */
  25. export function decodeAgentId(encoded: string): number {
  26. const scrambled = parseInt(encoded, 36);
  27. const original = (scrambled * MULTIPLIER_INV) % PRIME;
  28. return original;
  29. }