Compare commits

..
Author SHA1 Message Date
ShareVB c45a055643 fix: nosonar in unit tests 2024-06-16 13:57:24 +02:00
ShareVB 11206a52a1 fix(Mac Address Converter): update description 2024-06-16 13:57:07 +02:00
ShareVB 068d79a08f chore: fix strange corepack message
Fix corepack claiming strange thing : UsageError: This project is configured to use yarn because /home/runner/work/it-tools/it-tools/package.json has a "packageManager" field
2024-06-16 13:53:12 +02:00
ShareVB df049e2e69 Merge branch 'feat/mac-address-converter' of https://github.com/sharevb/it-tools into feat/mac-address-converter 2024-06-16 13:51:56 +02:00
ShareVB 743757761d feat(MAC Address Converter): add EUI-64 and IPv6 support
Fix #1146
2024-06-16 13:50:56 +02:00
sharevb 12b0dc100d Merge branch 'main' into feat/mac-address-converter 2024-05-15 22:28:00 +02:00
ShareVB d14371c5c2 fix: refactor with unit test 2024-05-15 22:09:37 +02:00
sharevb 00b85de1a0 Merge branch 'main' into feat/mac-address-converter 2024-02-04 14:17:02 +01:00
ShareVB 4598ebae09 feat(new tool): MAC Address Converter 2024-02-03 14:06:32 +01:00
16 changed files with 266 additions and 209 deletions

No files matched your search

+1
View File
@@ -117,6 +117,7 @@ declare module '@vue/runtime-core' {
ListConverter: typeof import('./src/tools/list-converter/list-converter.vue')['default']
LocaleSelector: typeof import('./src/modules/i18n/components/locale-selector.vue')['default']
LoremIpsumGenerator: typeof import('./src/tools/lorem-ipsum-generator/lorem-ipsum-generator.vue')['default']
MacAddressConverter: typeof import('./src/tools/mac-address-converter/mac-address-converter.vue')['default']
MacAddressGenerator: typeof import('./src/tools/mac-address-generator/mac-address-generator.vue')['default']
MacAddressLookup: typeof import('./src/tools/mac-address-lookup/mac-address-lookup.vue')['default']
MathEvaluator: typeof import('./src/tools/math-evaluator/math-evaluator.vue')['default']
+2 -2
View File
@@ -64,7 +64,6 @@
"highlight.js": "^11.7.0",
"iarna-toml-esm": "^3.0.5",
"ibantools": "^4.3.3",
"js-base64": "^3.7.6",
"json5": "^2.2.3",
"jwt-decode": "^3.1.2",
"libphonenumber-js": "^1.10.28",
@@ -138,5 +137,6 @@
"vitest": "^0.34.0",
"workbox-window": "^7.0.0",
"zx": "^7.2.1"
}
},
"packageManager": "pnpm@8.15.3"
}
+6 -13
View File
@@ -92,9 +92,6 @@ dependencies:
ibantools:
specifier: ^4.3.3
version: 4.3.3
js-base64:
specifier: ^3.7.6
version: 3.7.7
json5:
specifier: ^2.2.3
version: 2.2.3
@@ -3354,7 +3351,7 @@ packages:
dependencies:
'@unhead/dom': 0.5.1
'@unhead/schema': 0.5.1
'@vueuse/shared': 10.8.0(vue@3.3.4)
'@vueuse/shared': 10.7.2(vue@3.3.4)
unhead: 0.5.1
vue: 3.3.4
transitivePeerDependencies:
@@ -3996,10 +3993,10 @@ packages:
- vue
dev: false
/@vueuse/shared@10.8.0(vue@3.3.4):
resolution: {integrity: sha512-dUdy6zwHhULGxmr9YUg8e+EnB39gcM4Fe2oKBSrh3cOsV30JcMPtsyuspgFCUo5xxFNaeMf/W2yyKfST7Bg8oQ==}
/@vueuse/shared@10.7.2(vue@3.3.4):
resolution: {integrity: sha512-qFbXoxS44pi2FkgFjPvF4h7c9oMDutpyBdcJdMYIMg9XyXli2meFMuaKn+UMgsClo//Th6+beeCgqweT/79BVA==}
dependencies:
vue-demi: 0.14.7(vue@3.3.4)
vue-demi: 0.14.6(vue@3.3.4)
transitivePeerDependencies:
- '@vue/composition-api'
- vue
@@ -6475,10 +6472,6 @@ packages:
hasBin: true
dev: true
/js-base64@3.7.7:
resolution: {integrity: sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==}
dev: false
/js-beautify@1.14.6:
resolution: {integrity: sha512-GfofQY5zDp+cuHc+gsEXKPpNw2KbPddreEo35O6jT6i0RVK6LhsoYBhq5TvK4/n74wnA0QbK8gGd+jUZwTMKJw==}
engines: {node: '>=10'}
@@ -9158,8 +9151,8 @@ packages:
vue: 3.3.4
dev: false
/vue-demi@0.14.7(vue@3.3.4):
resolution: {integrity: sha512-EOG8KXDQNwkJILkx/gPcoL/7vH+hORoBaKgGe+6W7VFMvCYJfmF2dGbvgDroVnI8LU7/kTu8mbjRZGBU1z9NTA==}
/vue-demi@0.14.6(vue@3.3.4):
resolution: {integrity: sha512-8QA7wrYSHKaYgUxDA5ZC24w+eHm3sYCbp0EzcDwKqN3p6HqtTCGR/GVsPyZW92unff4UlcSh++lmqDWN3ZIq4w==}
engines: {node: '>=12'}
hasBin: true
requiresBuild: true
+1 -1
View File
@@ -48,7 +48,7 @@ const output = computed(() => transformer.value(input.value));
monospace
/>
<div overflow-auto>
<div>
<div mb-5px>
{{ outputLabel }}
</div>
+19 -72
View File
@@ -1,13 +1,8 @@
import { extension as getExtensionFromMimeType, extension as getMimeTypeFromExtension } from 'mime-types';
import { extension as getExtensionFromMime } from 'mime-types';
import type { Ref } from 'vue';
import _ from 'lodash';
export {
getMimeTypeFromBase64,
getMimeTypeFromExtension, getExtensionFromMimeType,
useDownloadFileFromBase64, useDownloadFileFromBase64Refs,
previewImageFromBase64,
};
export { getMimeTypeFromBase64, useDownloadFileFromBase64 };
const commonMimeTypesSignatures = {
'JVBERi0': 'application/pdf',
@@ -41,78 +36,30 @@ function getFileExtensionFromMimeType({
defaultExtension?: string
}) {
if (mimeType) {
return getExtensionFromMimeType(mimeType) ?? defaultExtension;
return getExtensionFromMime(mimeType) ?? defaultExtension;
}
return defaultExtension;
}
function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
{ sourceValue: string; filename?: string; extension?: string; fileMimeType?: string }) {
if (sourceValue === '') {
throw new Error('Base64 string is empty');
}
const defaultExtension = extension ?? 'txt';
const { mimeType } = getMimeTypeFromBase64({ base64String: sourceValue });
let base64String = sourceValue;
if (!mimeType) {
const targetMimeType = fileMimeType ?? getMimeTypeFromExtension(defaultExtension);
base64String = `data:${targetMimeType};base64,${sourceValue}`;
}
const cleanExtension = extension ?? getFileExtensionFromMimeType(
{ mimeType, defaultExtension });
let cleanFileName = filename ?? `file.${cleanExtension}`;
if (extension && !cleanFileName.endsWith(`.${extension}`)) {
cleanFileName = `${cleanFileName}.${cleanExtension}`;
}
const a = document.createElement('a');
a.href = base64String;
a.download = cleanFileName;
a.click();
}
function useDownloadFileFromBase64(
{ source, filename, extension, fileMimeType }:
{ source: Ref<string>; filename?: string; extension?: string; fileMimeType?: string }) {
function useDownloadFileFromBase64({ source, filename }: { source: Ref<string>; filename?: string }) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename, extension, fileMimeType });
if (source.value === '') {
throw new Error('Base64 string is empty');
}
const { mimeType } = getMimeTypeFromBase64({ base64String: source.value });
const base64String = mimeType
? source.value
: `data:text/plain;base64,${source.value}`;
const cleanFileName = filename ?? `file.${getFileExtensionFromMimeType({ mimeType })}`;
const a = document.createElement('a');
a.href = base64String;
a.download = cleanFileName;
a.click();
},
};
}
function useDownloadFileFromBase64Refs(
{ source, filename, extension }:
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
},
};
}
function previewImageFromBase64(base64String: string): HTMLImageElement {
if (base64String === '') {
throw new Error('Base64 string is empty');
}
const img = document.createElement('img');
img.src = base64String;
const container = document.createElement('div');
container.appendChild(img);
const previewContainer = document.getElementById('previewContainer');
if (previewContainer) {
previewContainer.innerHTML = '';
previewContainer.appendChild(container);
}
else {
throw new Error('Preview container element not found');
}
return img;
}
+1 -32
View File
@@ -1,8 +1,7 @@
import { useRouteQuery } from '@vueuse/router';
import { computed } from 'vue';
import { useStorage } from '@vueuse/core';
export { useQueryParam, useQueryParamOrStorage };
export { useQueryParam };
const transformers = {
number: {
@@ -17,12 +16,6 @@ const transformers = {
fromQuery: (value: string) => value.toLowerCase() === 'true',
toQuery: (value: boolean) => (value ? 'true' : 'false'),
},
object: {
fromQuery: (value: string) => {
return JSON.parse(value);
},
toQuery: (value: object) => JSON.stringify(value),
},
};
function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue: T }) {
@@ -40,27 +33,3 @@ function useQueryParam<T>({ name, defaultValue }: { name: string; defaultValue:
},
});
}
function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name: string; storageName: string; defaultValue: T }) {
const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
const storageRef = useStorage(storageName, defaultValue);
const proxyDefaultValue = transformer.toQuery(defaultValue as never);
const proxy = useRouteQuery(name, proxyDefaultValue);
const r = ref(defaultValue);
watch(r,
(value) => {
proxy.value = transformer.toQuery(value as never);
storageRef.value = value as never;
},
{ deep: true });
r.value = (proxy.value && proxy.value !== proxyDefaultValue
? transformer.fromQuery(proxy.value) as unknown as T
: storageRef.value as T) as never;
return r;
}
@@ -2,19 +2,12 @@
import { useBase64 } from '@vueuse/core';
import type { Ref } from 'vue';
import { useCopy } from '@/composable/copy';
import { getExtensionFromMimeType, getMimeTypeFromBase64, previewImageFromBase64, useDownloadFileFromBase64Refs } from '@/composable/downloadBase64';
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
import { useValidation } from '@/composable/validation';
import { isValidBase64 } from '@/utils/base64';
const fileName = ref('file');
const fileExtension = ref('');
const base64Input = ref('');
const { download } = useDownloadFileFromBase64Refs(
{
source: base64Input,
filename: fileName,
extension: fileExtension,
});
const { download } = useDownloadFileFromBase64({ source: base64Input });
const base64InputValidation = useValidation({
source: base64Input,
rules: [
@@ -25,35 +18,6 @@ const base64InputValidation = useValidation({
],
});
watch(
base64Input,
(newValue, _) => {
const { mimeType } = getMimeTypeFromBase64({ base64String: newValue });
if (mimeType) {
fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value;
}
},
);
function previewImage() {
if (!base64InputValidation.isValid) {
return;
}
try {
const image = previewImageFromBase64(base64Input.value);
image.style.maxWidth = '100%';
image.style.maxHeight = '400px';
const previewContainer = document.getElementById('previewContainer');
if (previewContainer) {
previewContainer.innerHTML = '';
previewContainer.appendChild(image);
}
}
catch (_) {
//
}
}
function downloadFile() {
if (!base64InputValidation.isValid) {
return;
@@ -80,24 +44,6 @@ async function onUpload(file: File) {
<template>
<c-card title="Base64 to file">
<n-grid cols="3" x-gap="12">
<n-gi span="2">
<c-input-text
v-model:value="fileName"
label="File Name"
placeholder="Download filename"
mb-2
/>
</n-gi>
<n-gi>
<c-input-text
v-model:value="fileExtension"
label="Extension"
placeholder="Extension"
mb-2
/>
</n-gi>
</n-grid>
<c-input-text
v-model:value="base64Input"
multiline
@@ -107,14 +53,7 @@ async function onUpload(file: File) {
mb-2
/>
<div flex justify-center py-2>
<div id="previewContainer" />
</div>
<div flex justify-center gap-3>
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="previewImage()">
Preview image
</c-button>
<div flex justify-center>
<c-button :disabled="base64Input === '' || !base64InputValidation.isValid" @click="downloadFile()">
Download file
</c-button>
+10 -3
View File
@@ -1,9 +1,8 @@
import { tool as base64FileConverter } from './base64-file-converter';
import { tool as base64StringConverter } from './base64-string-converter';
import { tool as basicAuthGenerator } from './basic-auth-generator';
import { tool as macAddressConverter } from './mac-address-converter';
import { tool as asciiTextDrawer } from './ascii-text-drawer';
import { tool as textToUnicode } from './text-to-unicode';
import { tool as safelinkDecoder } from './safelink-decoder';
import { tool as pdfSignatureChecker } from './pdf-signature-checker';
@@ -152,7 +151,15 @@ export const toolsByCategory: ToolCategory[] = [
},
{
name: 'Network',
components: [ipv4SubnetCalculator, ipv4AddressConverter, ipv4RangeExpander, macAddressLookup, macAddressGenerator, ipv6UlaGenerator],
components: [
ipv4SubnetCalculator,
ipv4AddressConverter,
ipv4RangeExpander,
macAddressLookup,
macAddressGenerator,
macAddressConverter,
ipv6UlaGenerator,
],
},
{
name: 'Math',
+2 -2
View File
@@ -39,7 +39,7 @@ const validation = useValidation({
{{ section.title }}
</th>
<tr v-for="{ claim, claimDescription, friendlyValue, value } in decodedJWT[section.key]" :key="claim + value">
<td class="claims" style="vertical-align: top;">
<td class="claims">
<span font-bold>
{{ claim }}
</span>
@@ -47,7 +47,7 @@ const validation = useValidation({
({{ claimDescription }})
</span>
</td>
<td style="word-wrap: break-word;word-break: break-all;">
<td>
<span>{{ value }}</span>
<span v-if="friendlyValue" ml-2 op-70>
({{ friendlyValue }})
+20
View File
@@ -0,0 +1,20 @@
import { Devices } from '@vicons/tabler';
import { defineTool } from '../tool';
export const tool = defineTool({
name: 'MAC Address Converter',
path: '/mac-address-converter',
description: 'Change the format of a MAC address and chose between different formats (EUI-48, EUI-64, IPv6)',
keywords: [
'converter',
'mac',
'address',
'format',
'link-local',
'ipv6',
'eui-48',
'eui-64',
],
component: () => import('./mac-address-converter.vue'),
icon: Devices,
});
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import {
convertMacCISCO, convertMacCanonical,
convertMacCanonicalIEEE, convertMacCanonicalIETF,
convertMacToEUI64CISCO, convertMacToEUI64CanonicalIEEE,
convertMacToEUI64CanonicalIETF, convertMacToLinkLocalIPv6,
convertMacToNumber,
} from './mac-address-converter.service';
describe('mac-address-converter', () => {
it('Convert MAC Address to given format', async () => {
expect(convertMacCanonical('')).to.equal('');
const macValue = '00:0a:95:9d:68:16';
expect(convertMacCanonicalIETF(macValue)).to.equal('00:0a:95:9d:68:16');
expect(convertMacCanonical(macValue)).to.equal('00.0a.95.9d.68.16');
expect(convertMacCanonicalIEEE(macValue)).to.equal('00-0A-95-9D-68-16');
expect(convertMacCISCO(macValue)).to.equal('000a.959d.6816');
expect(convertMacToEUI64CanonicalIETF(macValue, true)).to.equal('02:0a:95:ff:fe:9d:68:16'); // NOSONAR
expect(convertMacToEUI64CanonicalIETF(macValue, false)).to.equal('00:0a:95:ff:fe:9d:68:16'); // NOSONAR
expect(convertMacToEUI64CanonicalIEEE(macValue, true)).to.equal('02-0A-95-FF-FE-9D-68-16');
expect(convertMacToEUI64CanonicalIEEE(macValue, false)).to.equal('00-0A-95-FF-FE-9D-68-16');
expect(convertMacToEUI64CISCO(macValue, true)).to.equal('020a.95ff.fe9d.6816');
expect(convertMacToEUI64CISCO(macValue, false)).to.equal('000a.95ff.fe9d.6816');
expect(convertMacToNumber(macValue)).to.equal(45459793942);
expect(convertMacToLinkLocalIPv6(macValue)).to.equal(':fe80::20a:95ff:fe9d:6816');
});
});
@@ -0,0 +1,59 @@
function convertMac(mac: string, group: number = 2, char: string = ':'): string {
mac = mac.replace(/[\W_]+/g, '');
return mac.match(new RegExp(`.{1,${group}}`, 'g'))?.join(char) || '';
}
function convertMacToEUI64(mac: string, ipv6: boolean) {
const macIETF = convertMac(mac);
// Split the MAC address into an array of hex values
const macArray = macIETF.split(':').map(hex => Number.parseInt(hex, 16));
// For IPv6, invert the 7th bit of the first byte
if (ipv6) {
macArray[0] ^= 0x02;
}
// Insert FFFE in the middle
const eui64Array = [
macArray[0], macArray[1], macArray[2],
0xFF, 0xFE,
macArray[3], macArray[4], macArray[5],
];
// Convert the array to a colon-separated string
const eui64 = eui64Array.map(byte => byte.toString(16).padStart(2, '0')).join(':');
// Group into IPv6 EUI-64 format (XXXX:XXFF:FEXX:XXXX)
return eui64.replace(/:/g, '').match(/.{1,4}/g)!.join(':');
}
export function convertMacToEUI64CanonicalIETF(mac: string, ipv6: boolean) {
return convertMac(convertMacToEUI64(mac, ipv6).toLocaleLowerCase());
}
export function convertMacToEUI64CanonicalIEEE(mac: string, ipv6: boolean) {
return convertMac(convertMacToEUI64(mac, ipv6).toLocaleUpperCase(), 2, '-');
}
export function convertMacToEUI64CISCO(mac: string, ipv6: boolean) {
return convertMac(convertMacToEUI64(mac, ipv6).toLocaleLowerCase(), 4, '.');
}
export function convertMacToLinkLocalIPv6(mac: string) {
return `:fe80::${convertMac(convertMacToEUI64(mac, true).toLocaleLowerCase(), 4, ':').replace(/^0/g, '')}`;
}
export function convertMacToNumber(mac: string) {
mac = mac.replace(/[\W_]+/g, '');
return Number.parseInt(mac, 16);
}
export function convertMacCanonicalIETF(mac: string): string {
return convertMac(mac.toLocaleLowerCase());
};
export function convertMacCanonical(mac: string): string {
return convertMac(mac, 2, '.');
};
export function convertMacCanonicalIEEE(mac: string): string {
return convertMac(mac.toLocaleUpperCase(), 2, '-');
};
export function convertMacCISCO(mac: string): string {
return convertMac(mac.toLocaleLowerCase(), 4, '.');
};
@@ -0,0 +1,101 @@
<script setup lang="ts">
import InputCopyable from '../../components/InputCopyable.vue';
import {
convertMacCISCO, convertMacCanonical,
convertMacCanonicalIEEE, convertMacCanonicalIETF,
convertMacToEUI64CISCO, convertMacToEUI64CanonicalIEEE,
convertMacToEUI64CanonicalIETF, convertMacToLinkLocalIPv6,
convertMacToNumber,
} from './mac-address-converter.service';
const input = ref('AA:BB:CC:DD:EE:FF');
const formats = computed(() => [
{
label: 'Canonical IETF Format:',
value: convertMacCanonicalIETF(input.value),
},
{
label: 'Canonical Format:',
value: convertMacCanonical(input.value),
},
{
label: 'Canonical IEEE Format:',
value: convertMacCanonicalIEEE(input.value),
},
{
label: 'Cisco:',
value: convertMacCISCO(input.value),
},
{
label: 'Hex:',
value: convertMacToNumber(input.value).toString(16),
},
{
label: 'Decimal:',
value: convertMacToNumber(input.value).toString(10),
},
{
label: 'EUI-64 Canonical IETF Format:',
value: convertMacToEUI64CanonicalIETF(input.value, false),
},
{
label: 'EUI-64 Canonical IEEE Format:',
value: convertMacToEUI64CanonicalIEEE(input.value, false),
},
{
label: 'EUI-64 Cisco:',
value: convertMacToEUI64CISCO(input.value, false),
},
{
label: 'EUI-64 IPv6 Canonical IETF Format:',
value: convertMacToEUI64CanonicalIETF(input.value, true),
},
{
label: 'EUI-64 IPv6 Canonical IEEE Format:',
value: convertMacToEUI64CanonicalIEEE(input.value, true),
},
{
label: 'EUI-64 IPv6 Cisco:',
value: convertMacToEUI64CISCO(input.value, true),
},
{
label: 'Link-Local IPv6:',
value: convertMacToLinkLocalIPv6(input.value),
},
]);
const inputLabelAlignmentConfig = {
labelPosition: 'left',
labelWidth: '120px',
labelAlign: 'right',
};
</script>
<template>
<c-card>
<c-input-text
v-model:value="input"
label="MAC address:"
size="large"
placeholder="Type a MAC address"
clearable
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"
mb-5
/>
<div my-16px divider />
<InputCopyable
v-for="format in formats"
:key="format.label"
:value="format.value"
:label="format.label"
v-bind="inputLabelAlignmentConfig"
mb-1
/>
</c-card>
</template>
@@ -7,18 +7,13 @@ import TokenDisplay from './token-display.vue';
import { useStyleStore } from '@/stores/style.store';
import InputCopyable from '@/components/InputCopyable.vue';
import { computedRefreshable } from '@/composable/computedRefreshable';
import { useQueryParamOrStorage } from '@/composable/queryParams';
const now = useTimestamp();
const interval = computed(() => (now.value / 1000) % 30);
const theme = useThemeVars();
const styleStore = useStyleStore();
const secret = useQueryParamOrStorage({
name: 'secret',
storageName: 'otp-gen:secret',
defaultValue: generateSecret(),
});
const secret = ref(generateSecret());
function refreshSecret() {
secret.value = generateSecret();
+6 -7
View File
@@ -38,8 +38,7 @@ describe('base64 utils', () => {
it('should throw for incorrect base64 string', () => {
expect(() => base64ToText('a')).to.throw('Incorrect base64 string');
// should not really be false because trimming of space is now implied
// expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
expect(() => base64ToText(' ')).to.throw('Incorrect base64 string');
expect(() => base64ToText('é')).to.throw('Incorrect base64 string');
// missing final '='
expect(() => base64ToText('bG9yZW0gaXBzdW0')).to.throw('Incorrect base64 string');
@@ -57,17 +56,17 @@ describe('base64 utils', () => {
it('should return false for incorrect base64 string', () => {
expect(isValidBase64('a')).to.eql(false);
expect(isValidBase64(' ')).to.eql(false);
expect(isValidBase64('é')).to.eql(false);
expect(isValidBase64('data:text/plain;notbase64,YQ==')).to.eql(false);
// missing final '='
expect(isValidBase64('bG9yZW0gaXBzdW0')).to.eql(false);
});
it('should return true for untrimmed correct base64 string', () => {
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(true);
expect(isValidBase64(' LTE=')).to.eql(true);
expect(isValidBase64(' YQ== ')).to.eql(true);
expect(isValidBase64(' ')).to.eql(true);
it('should return false for untrimmed correct base64 string', () => {
expect(isValidBase64('bG9yZW0gaXBzdW0= ')).to.eql(false);
expect(isValidBase64(' LTE=')).to.eql(false);
expect(isValidBase64(' YQ== ')).to.eql(false);
});
});
+4 -7
View File
@@ -1,9 +1,7 @@
import { Base64 } from 'js-base64';
export { textToBase64, base64ToText, isValidBase64, removePotentialDataAndMimePrefix };
function textToBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boolean } = {}) {
const encoded = Base64.encode(str);
const encoded = window.btoa(str);
return makeUrlSafe ? makeUriSafe(encoded) : encoded;
}
@@ -18,7 +16,7 @@ function base64ToText(str: string, { makeUrlSafe = false }: { makeUrlSafe?: bool
}
try {
return Base64.decode(cleanStr);
return window.atob(cleanStr);
}
catch (_) {
throw new Error('Incorrect base64 string');
@@ -36,11 +34,10 @@ function isValidBase64(str: string, { makeUrlSafe = false }: { makeUrlSafe?: boo
}
try {
const reEncodedBase64 = Base64.fromUint8Array(Base64.toUint8Array(cleanStr));
if (makeUrlSafe) {
return removePotentialPadding(reEncodedBase64) === cleanStr;
return removePotentialPadding(window.btoa(window.atob(cleanStr))) === cleanStr;
}
return reEncodedBase64 === cleanStr.replace(/\s/g, '');
return window.btoa(window.atob(cleanStr)) === cleanStr;
}
catch (err) {
return false;