MatrixAI / js-id

ID generation for JavaScript & TypeScript Applications
https://polykey.com
Apache License 2.0
10 stars 1 forks source link

Allow Id to have arbitrary length instead of 16 byte limit, also add in POJO and Map tests #10

Closed CMCDragonkai closed 2 years ago

CMCDragonkai commented 2 years ago

Description

As discussed in https://github.com/MatrixAI/js-polykey/issues/254, we want Id to be usable for NodeId as well. In such a case, we don't actually want the 16 byte limit that we have in our utils.ts atm. This is only relevant to UUID. So the limit can be constraint to UUID conversions, and all other functions can operate more freely.

Issues Fixed

Tasks

  1. [x] Add 16 byte check to toUUID, and throw RangeError if the Id is not 16 bytes
  2. [x] Remove 16 byte limit from other conversion utilities like string, buffer and multibase
  3. [x] Create tests for Id.test.ts to test Id creation byitself
  4. [x] Add POJO and Map tests to show that Id can be used as Map keys, and POJO keys without any problems

Final checklist

CMCDragonkai commented 2 years ago

This is ready, expect to use Id as NodeId in this way:

function publicKeyToFingerprintBytes(
  publicKey: PublicKey,
): PublicKeyFingerprintBytes {
  const fString = pki.getPublicKeyFingerprint(publicKey, {
    type: 'SubjectPublicKeyInfo',
    md: md.sha256.create(),
    encoding: 'binary',
  });
  return fString;
}

const b = Buffer.from(publicKeyToFingerprintBytes(publicKey), 'binary');

const nodeId = Id.create(b);

Note that the publicKeyToFingerPrintBytes currently returns a string due to how node-forge works. So we have to convert it to buffer which is an Uint8Array, and therefore can be used in nodeId.

CMCDragonkai commented 2 years ago

Actually there's a better function:

  const fString = publicKeyToFingerprintBytes(publicKey);
  const fTypedArray = forgeUtil.binary.raw.decode(fString);

Then Id.create(fTypedArray) should work too.