|
1 | 1 | /** |
2 | | - * Encodes a URL string to Base64 format for safe URL parameter usage |
| 2 | + * Encodes a URL string to URL-safe Base64 format for safe URL parameter usage |
| 3 | + * Uses URL-safe Base64 encoding (RFC 4648 §5) by replacing + with -, / with _, and removing padding = |
3 | 4 | * @param url - The URL string to encode |
4 | | - * @returns Base64 encoded string |
| 5 | + * @returns URL-safe Base64 encoded string |
5 | 6 | */ |
6 | 7 | export const encodeUrlToBase64 = (url: string): string => { |
7 | 8 | try { |
8 | 9 | // Use btoa for browser-compatible Base64 encoding |
9 | 10 | // First encode to handle UTF-8 characters properly |
10 | 11 | const utf8Bytes = new TextEncoder().encode(url); |
11 | 12 | const binaryString = Array.from(utf8Bytes, byte => String.fromCharCode(byte)).join(''); |
12 | | - return btoa(binaryString); |
| 13 | + const base64 = btoa(binaryString); |
| 14 | + // Convert to URL-safe Base64 by replacing + with -, / with _, and removing padding = |
| 15 | + return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); |
13 | 16 | } catch (error) { |
14 | 17 | console.error('Error encoding URL to Base64:', error); |
15 | 18 | throw new Error('Failed to encode URL to Base64'); |
16 | 19 | } |
17 | 20 | }; |
18 | 21 |
|
19 | 22 | /** |
20 | | - * Decodes a Base64 encoded URL string |
| 23 | + * Decodes a URL-safe Base64 encoded URL string |
| 24 | + * Handles both URL-safe and standard Base64 formats |
21 | 25 | * @param encodedUrl - The Base64 encoded URL string |
22 | 26 | * @returns Decoded URL string |
23 | 27 | */ |
24 | 28 | export const decodeBase64ToUrl = (encodedUrl: string): string => { |
25 | 29 | try { |
| 30 | + // Convert URL-safe Base64 back to standard Base64 |
| 31 | + let base64 = encodedUrl.replace(/-/g, '+').replace(/_/g, '/'); |
| 32 | + // Add padding if necessary |
| 33 | + while (base64.length % 4 !== 0) { |
| 34 | + base64 += '='; |
| 35 | + } |
26 | 36 | // Use atob for browser-compatible Base64 decoding |
27 | | - const binaryString = atob(encodedUrl); |
| 37 | + const binaryString = atob(base64); |
28 | 38 | const bytes = Uint8Array.from(binaryString, char => char.charCodeAt(0)); |
29 | 39 | return new TextDecoder().decode(bytes); |
30 | 40 | } catch (error) { |
|
0 commit comments