Commit 9464eaa4 authored by Jukkrapong Ponharn's avatar Jukkrapong Ponharn

Implement UTF-8 safe Base64 encode/decode functions and update PolicyRequest class to use them

parent 2f8cd049
import { encode as base64Encode, decode as base64Decode } from 'base-64';
import axios from 'axios';
/**
......@@ -81,6 +80,44 @@ async function getPublicIP(): Promise<string | null> {
}
}
// UTF-8 safe Base64 encode/decode helpers (Node + browser)
function base64EncodeUtf8(input: string): string {
try {
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
return Buffer.from(input, 'utf8').toString('base64');
}
const btoaFn = (globalThis as any).btoa;
if (typeof btoaFn === 'function') {
// encodeURIComponent -> percent-encode -> unescape to binary string
return btoaFn(unescape(encodeURIComponent(input)));
}
} catch (e) {
// fallthrough to throw below
}
throw new Error('No available method to perform base64 encoding');
}
function base64DecodeUtf8(b64: string): string {
try {
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
return Buffer.from(b64, 'base64').toString('utf8');
}
const atobFn = (globalThis as any).atob;
if (typeof atobFn === 'function') {
const binary = atobFn(b64);
// convert binary string to percent-encoded string, then decode
const percentEncoded = Array.prototype.map.call(binary, (ch: string) => {
const code = ch.charCodeAt(0).toString(16).toUpperCase();
return '%' + (code.length < 2 ? '0' + code : code);
}).join('');
return decodeURIComponent(percentEncoded);
}
} catch (e) {
// fallthrough to throw below
}
throw new Error('No available method to perform base64 decoding');
}
/**
* Policy Request Instance Configuration
*/
......@@ -179,7 +216,7 @@ export class PolicyRequest {
};
const jsonString = JSON.stringify(data);
return base64Encode(jsonString);
return base64EncodeUtf8(jsonString);
}
/**
......@@ -217,7 +254,7 @@ export class PolicyRequest {
*/
static decode(base64String: string): PolicyRequestData {
try {
const decoded = base64Decode(base64String);
const decoded = base64DecodeUtf8(base64String);
return JSON.parse(decoded);
} catch (error) {
throw new Error(
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment