base64.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Browser- and Node-safe base64 / base64url helpers used by the in-browser
  2. // config tools. No Node `Buffer` so the same code runs in the browser and in
  3. // vitest (Node). `btoa`/`atob` and `TextEncoder`/`TextDecoder` are available in
  4. // both environments.
  5. export function bytesToBase64(bytes: Uint8Array): string {
  6. let binary = '';
  7. for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
  8. return btoa(binary);
  9. }
  10. /** Decode standard or URL-safe base64, tolerating missing padding. */
  11. export function base64ToBytes(b64: string): Uint8Array {
  12. const normalized = b64.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
  13. const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
  14. const binary = atob(padded);
  15. const out = new Uint8Array(binary.length);
  16. for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
  17. return out;
  18. }
  19. /** Encode bytes as URL-safe base64 with no padding (xray's key format). */
  20. export function bytesToBase64Url(bytes: Uint8Array): string {
  21. return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  22. }
  23. export function base64UrlToBytes(s: string): Uint8Array {
  24. return base64ToBytes(s);
  25. }
  26. const encoder = new TextEncoder();
  27. const decoder = new TextDecoder();
  28. /** UTF-8 text → standard base64 (used by vmess:// links). */
  29. export function textToBase64(text: string): string {
  30. return bytesToBase64(encoder.encode(text));
  31. }
  32. /** standard/URL-safe base64 → UTF-8 text. */
  33. export function base64ToText(b64: string): string {
  34. return decoder.decode(base64ToBytes(b64));
  35. }