Skip to content

Commit

Permalink
fix: EncodePath utf8 (#549)
Browse files Browse the repository at this point in the history
rrr523 authored May 21, 2024
1 parent 20da72d commit 34aa1c7
Showing 3 changed files with 23 additions and 11 deletions.
5 changes: 5 additions & 0 deletions .changeset/perfect-panthers-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@bnb-chain/greenfield-js-sdk': patch
---

feat: EncodePath UTF-8
23 changes: 12 additions & 11 deletions packages/js-sdk/src/clients/spclient/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { AuthType, ReqMeta } from '@/types/auth';
import { hexlify, joinSignature } from '@ethersproject/bytes';
import { arrayify, hexlify, joinSignature } from '@ethersproject/bytes';
import { SigningKey } from '@ethersproject/signing-key';
import { toUtf8Bytes } from '@ethersproject/strings';
import { ed25519 } from '@noble/curves/ed25519';
import { Headers } from 'cross-fetch';
import { keccak256 } from 'ethereum-cryptography/keccak.js';
@@ -58,7 +59,8 @@ export const getCanonicalRequest = (reqMeta: Partial<ReqMeta>, reqHeaders: Heade
};

export const getAuthorization = (canonicalRequest: string, authType: AuthType) => {
// console.log('canonicalRequest', canonicalRequest);
// eslint-disable-next-line no-console
console.log('canonicalRequest', canonicalRequest);

const unsignedMsg = getMsgToSign(utf8ToBytes(canonicalRequest));
let authorization = '';
@@ -170,6 +172,7 @@ export const getMsgToSign = (unsignedBytes: Uint8Array): Uint8Array => {
};

export const encodePath = (pathName: string) => {
debugger;
const reservedNames = /^[a-zA-Z0-9-_.~/]+$/;
if (reservedNames.test(pathName)) {
return pathName;
@@ -196,16 +199,14 @@ export const encodePath = (pathName: string) => {
continue;

// others characters need to be encoded
default:
// . ! @ # $ % ^ & * ) ( - + = { } [ ] / " , ' < > ~ \ .` ? : ; | \\
if (/[.!@#\$%\^&\*\)\(\-+=\{\}\[\]\/\",'<>~\·`\?:;|\\]+$/.test(s)) {
// english characters
const hexStr = s.charCodeAt(0).toString(16);
encodedPathName += '%' + hexStr.toUpperCase();
} else {
// others characters
encodedPathName += encodeURI(s);
default: {
const u = toUtf8Bytes(s);

for (let i = 0; i < u.length; i++) {
const hexStr = hexlify(u[i]);
encodedPathName += '%' + hexStr.slice(2).toUpperCase();
}
}
}
}
return encodedPathName;
6 changes: 6 additions & 0 deletions packages/js-sdk/tests/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -12,6 +12,12 @@ describe('encodePaths', () => {

it('encode chinese chars', () => {
expect(encodePath('中文')).equals('%E4%B8%AD%E6%96%87');

expect(encodePath('·')).equals('%C2%B7');

expect(encodePath('。,!·#@……*?《》+')).equals(
'%E3%80%82%EF%BC%8C%EF%BC%81%C2%B7%23%40%E2%80%A6%E2%80%A6%2A%EF%BC%9F%E3%80%8A%E3%80%8B%2B',
);
});

it('encode complex utf-8 chars', () => {

0 comments on commit 34aa1c7

Please sign in to comment.