Skip to content

Commit

Permalink
Merge pull request #8 from Holo-Host/2021-02-15-add-base64-charset-check
Browse files Browse the repository at this point in the history
add holohash base64 character set check and tests
  • Loading branch information
peeech committed Feb 15, 2021
2 parents baff6d3 + 2bb8019 commit c270dff
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ const HOLO_HASH_HEADER_PREFIX = Buffer.from(new Uint8Array([0x84, 0x29, 0x24]).b
const HOLO_HASH_ENTRY_PREFIX = Buffer.from(new Uint8Array([0x84, 0x21, 0x24]).buffer);
const HOLO_HASH_DNA_PREFIX = Buffer.from(new Uint8Array([0x84, 0x2d, 0x24]).buffer);

const HOLO_BASE64_CHAR_SET = /^[A-Za-z0-9\-_]+$/;

const getHoloHashPrefix = holoHashType => {
let holoHashPrefix;
switch (holoHashType) {
Expand Down Expand Up @@ -46,6 +48,12 @@ function check_length(buf, expectedLength) {
return buf;
}

function check_charset(string) {
if (! HOLO_BASE64_CHAR_SET.test(string))
throw new Error(`String ${string} contains characters from outside of Holo base64 character set. Make sure HoloHash base64 encoded string contains only [A-Za-z0-9\-_]`);
return string;
}

function convert_b64_to_holohash_b64(rawBase64) {
let holoHashbase64 = '';
const len = rawBase64.length;
Expand Down Expand Up @@ -120,6 +128,7 @@ const Codec = {
return "u" + convert_b64_to_holohash_b64(rawBase64);
},
decode: (base64) => {
check_charset(base64);
const buf = Buffer.from(base64.slice(1), "base64").slice(3, -4);
check_length(Buffer.from(buf), 32);
return buf;
Expand Down
13 changes: 12 additions & 1 deletion tests/test_codec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ describe("Codec.AgentId", () => {
});
});

it("should encode and decode back agent id", async () => {
let string = "uhCAkkeIowX20hXW-9wMyh0tQY5Y73RybHi1BdpKdIdbD26Dl_xwq";
let result = Codec.AgentId.encode(Codec.AgentId.decode(string));
expect(result).to.equal(string);
});

it("should throw an error when decoding string with chars outside of Holo base64 set", async () => {
let string = "uhCAkkeIowX20hXW+9wMyh0tQY5Y73RybHi1BdpKdIdbD26Dl/xwq";
expect(() => Codec.AgentId.decode(string)).to.throw();
});

describe("Codec.Base36", () => {
it("should decode agent ID using base36 and then encode agent ID back into base36", async () => {
const urlAgentId = "wjzlh5yt3uk0mzpcor0i12ol0rrpxdydzggt4b2fvr8yealc";
Expand Down Expand Up @@ -94,4 +105,4 @@ describe("Codec.Digest", () => {

expect(Codec.Digest.encode(jsonData)).to.equal(hashString);
});
});
});

0 comments on commit c270dff

Please sign in to comment.