Skip to content

Commit

Permalink
[PM-3660] chore: move guid utils away from platform utils
Browse files Browse the repository at this point in the history
  • Loading branch information
coroiu committed Sep 7, 2023
1 parent dc9494a commit 4ebf3ac
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 113 deletions.
98 changes: 0 additions & 98 deletions libs/common/src/platform/misc/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ export class Utils {
["google.com", new Set(["script.google.com"])],
]);

/** Used by guidToStandardFormat */
private static byteToHex: string[] = [];

static init() {
if (Utils.inited) {
return;
Expand All @@ -63,10 +60,6 @@ export class Utils {
// If it's not browser or node then it must be a service worker
Utils.global = self;
}

for (let i = 0; i < 256; ++i) {
Utils.byteToHex.push((i + 0x100).toString(16).substring(1));
}
}

static fromB64ToArray(str: string): Uint8Array {
Expand Down Expand Up @@ -584,97 +577,6 @@ export class Utils {

return null;
}

/*
License for: guidToRawFormat, guidToStandardFormat
Source: https://github.com/uuidjs/uuid/
The MIT License (MIT)
Copyright (c) 2010-2020 Robert Kieffer and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

/** Convert standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID to raw 16 byte array. */
static guidToRawFormat(guid: string) {
if (!Utils.isGuid(guid)) {
throw TypeError("GUID parameter is invalid");
}

let v;
const arr = new Uint8Array(16);

// Parse ########-....-....-....-............
arr[0] = (v = parseInt(guid.slice(0, 8), 16)) >>> 24;
arr[1] = (v >>> 16) & 0xff;
arr[2] = (v >>> 8) & 0xff;
arr[3] = v & 0xff;

// Parse ........-####-....-....-............
arr[4] = (v = parseInt(guid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff;

// Parse ........-....-####-....-............
arr[6] = (v = parseInt(guid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff;

// Parse ........-....-....-####-............
arr[8] = (v = parseInt(guid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff;

// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = ((v = parseInt(guid.slice(24, 36), 16)) / 0x10000000000) & 0xff;
arr[11] = (v / 0x100000000) & 0xff;
arr[12] = (v >>> 24) & 0xff;
arr[13] = (v >>> 16) & 0xff;
arr[14] = (v >>> 8) & 0xff;
arr[15] = v & 0xff;

return arr;
}

/** Convert raw 16 byte array to standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID. */
static guidToStandardFormat(bufferSource: BufferSource) {
const arr =
bufferSource instanceof ArrayBuffer
? new Uint8Array(bufferSource)
: new Uint8Array(bufferSource.buffer);
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
const guid = (
Utils.byteToHex[arr[0]] +
Utils.byteToHex[arr[1]] +
Utils.byteToHex[arr[2]] +
Utils.byteToHex[arr[3]] +
"-" +
Utils.byteToHex[arr[4]] +
Utils.byteToHex[arr[5]] +
"-" +
Utils.byteToHex[arr[6]] +
Utils.byteToHex[arr[7]] +
"-" +
Utils.byteToHex[arr[8]] +
Utils.byteToHex[arr[9]] +
"-" +
Utils.byteToHex[arr[10]] +
Utils.byteToHex[arr[11]] +
Utils.byteToHex[arr[12]] +
Utils.byteToHex[arr[13]] +
Utils.byteToHex[arr[14]] +
Utils.byteToHex[arr[15]]
).toLowerCase();

// Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!Utils.isGuid(guid)) {
throw TypeError("Converted GUID is invalid");
}

return guid;
}
}

Utils.init();
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { LoginView } from "../../models/view/login.view";

import { AAGUID, Fido2AuthenticatorService } from "./fido2-authenticator.service";
import { Fido2Utils } from "./fido2-utils";
import { guidToRawFormat } from "./guid-utils";

const RpId = "bitwarden.com";

Expand Down Expand Up @@ -112,7 +113,7 @@ describe("FidoAuthenticatorService", () => {
params = await createParams({
excludeCredentialDescriptorList: [
{
id: Utils.guidToRawFormat(excludedCipher.login.fido2Key.nonDiscoverableId),
id: guidToRawFormat(excludedCipher.login.fido2Key.nonDiscoverableId),
type: "public-key",
},
],
Expand Down Expand Up @@ -186,7 +187,7 @@ describe("FidoAuthenticatorService", () => {
excludedCipherView = createCipherView();
params = await createParams({
excludeCredentialDescriptorList: [
{ id: Utils.guidToRawFormat(excludedCipherView.id), type: "public-key" },
{ id: guidToRawFormat(excludedCipherView.id), type: "public-key" },
],
});
cipherService.get.mockImplementation(async (id) =>
Expand Down Expand Up @@ -633,7 +634,7 @@ describe("FidoAuthenticatorService", () => {
credentialId = Utils.newGuid();
params = await createParams({
allowCredentialDescriptorList: [
{ id: Utils.guidToRawFormat(credentialId), type: "public-key" },
{ id: guidToRawFormat(credentialId), type: "public-key" },
],
rpId: RpId,
});
Expand Down Expand Up @@ -709,7 +710,7 @@ describe("FidoAuthenticatorService", () => {
];
params = await createParams({
allowCredentialDescriptorList: credentialIds.map((credentialId) => ({
id: Utils.guidToRawFormat(credentialId),
id: guidToRawFormat(credentialId),
type: "public-key",
})),
rpId: RpId,
Expand Down Expand Up @@ -789,7 +790,7 @@ describe("FidoAuthenticatorService", () => {
selectedCredentialId = credentialIds[0];
params = await createParams({
allowCredentialDescriptorList: credentialIds.map((credentialId) => ({
id: Utils.guidToRawFormat(credentialId),
id: guidToRawFormat(credentialId),
type: "public-key",
})),
rpId: RpId,
Expand Down Expand Up @@ -842,7 +843,7 @@ describe("FidoAuthenticatorService", () => {
const flags = encAuthData.slice(32, 33);
const counter = encAuthData.slice(33, 37);

expect(result.selectedCredential.id).toEqual(Utils.guidToRawFormat(selectedCredentialId));
expect(result.selectedCredential.id).toEqual(guidToRawFormat(selectedCredentialId));
expect(result.selectedCredential.userHandle).toEqual(
Fido2Utils.stringToBuffer(fido2Keys[0].userHandle)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { Fido2KeyView } from "../../models/view/fido2-key.view";

import { joseToDer } from "./ecdsa-utils";
import { Fido2Utils } from "./fido2-utils";
import { guidToRawFormat, guidToStandardFormat } from "./guid-utils";

// AAGUID: 6e8248d5-b479-40db-a3d8-11116f7e8349
export const AAGUID = new Uint8Array([
Expand Down Expand Up @@ -185,7 +186,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr

const authData = await generateAuthData({
rpId: params.rpEntity.id,
credentialId: Utils.guidToRawFormat(credentialId),
credentialId: guidToRawFormat(credentialId),
counter: fido2Key.counter,
userPresence: true,
userVerification: userVerified,
Expand All @@ -200,7 +201,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
);

return {
credentialId: Utils.guidToRawFormat(credentialId),
credentialId: guidToRawFormat(credentialId),
attestationObject,
authData,
publicKeyAlgorithm: -7,
Expand Down Expand Up @@ -295,7 +296,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr

const authenticatorData = await generateAuthData({
rpId: selectedFido2Key.rpId,
credentialId: Utils.guidToRawFormat(selectedCredentialId),
credentialId: guidToRawFormat(selectedCredentialId),
counter: selectedFido2Key.counter,
userPresence: true,
userVerification: userVerified,
Expand All @@ -310,7 +311,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
return {
authenticatorData,
selectedCredential: {
id: Utils.guidToRawFormat(selectedCredentialId),
id: guidToRawFormat(selectedCredentialId),
userHandle: Fido2Utils.stringToBuffer(selectedFido2Key.userHandle),
},
signature,
Expand All @@ -334,7 +335,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr

for (const credential of credentials) {
try {
ids.push(Utils.guidToStandardFormat(credential.id));
ids.push(guidToStandardFormat(credential.id));
// eslint-disable-next-line no-empty
} catch {}
}
Expand Down Expand Up @@ -365,7 +366,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr

for (const credential of credentials) {
try {
ids.push(Utils.guidToStandardFormat(credential.id));
ids.push(guidToStandardFormat(credential.id));
// eslint-disable-next-line no-empty
} catch {}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { Fido2AuthenticatorService } from "./fido2-authenticator.service";
import { Fido2ClientService } from "./fido2-client.service";
import { Fido2Utils } from "./fido2-utils";
import { guidToRawFormat } from "./guid-utils";

const RpId = "bitwarden.com";

Expand Down Expand Up @@ -235,7 +236,7 @@ describe("FidoAuthenticatorService", () => {

function createAuthenticatorMakeResult(): Fido2AuthenticatorMakeCredentialResult {
return {
credentialId: Utils.guidToRawFormat(Utils.newGuid()),
credentialId: guidToRawFormat(Utils.newGuid()),
attestationObject: randomBytes(128),
authData: randomBytes(64),
publicKeyAlgorithm: -7,
Expand Down Expand Up @@ -346,8 +347,8 @@ describe("FidoAuthenticatorService", () => {
describe("assert non-discoverable credential", () => {
it("should call authenticator.assertCredential", async () => {
const allowedCredentialIds = [
Fido2Utils.bufferToString(Utils.guidToRawFormat(Utils.newGuid())),
Fido2Utils.bufferToString(Utils.guidToRawFormat(Utils.newGuid())),
Fido2Utils.bufferToString(guidToRawFormat(Utils.newGuid())),
Fido2Utils.bufferToString(guidToRawFormat(Utils.newGuid())),
Fido2Utils.bufferToString(Utils.fromByteStringToArray("not-a-guid")),
];
const params = createParams({
Expand Down
95 changes: 95 additions & 0 deletions libs/common/src/vault/services/fido2/guid-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
License for: guidToRawFormat, guidToStandardFormat
Source: https://github.com/uuidjs/uuid/
The MIT License (MIT)
Copyright (c) 2010-2020 Robert Kieffer and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/

import { Utils } from "../../../platform/misc/utils";

/** Private array used for optimization */
const byteToHex = Array.from({ length: 256 }, (_, i) => (i + 0x100).toString(16).substring(1));

/** Convert standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID to raw 16 byte array. */
export function guidToRawFormat(guid: string) {
if (!Utils.isGuid(guid)) {
throw TypeError("GUID parameter is invalid");
}

let v;
const arr = new Uint8Array(16);

// Parse ########-....-....-....-............
arr[0] = (v = parseInt(guid.slice(0, 8), 16)) >>> 24;
arr[1] = (v >>> 16) & 0xff;
arr[2] = (v >>> 8) & 0xff;
arr[3] = v & 0xff;

// Parse ........-####-....-....-............
arr[4] = (v = parseInt(guid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff;

// Parse ........-....-####-....-............
arr[6] = (v = parseInt(guid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff;

// Parse ........-....-....-####-............
arr[8] = (v = parseInt(guid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff;

// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = ((v = parseInt(guid.slice(24, 36), 16)) / 0x10000000000) & 0xff;
arr[11] = (v / 0x100000000) & 0xff;
arr[12] = (v >>> 24) & 0xff;
arr[13] = (v >>> 16) & 0xff;
arr[14] = (v >>> 8) & 0xff;
arr[15] = v & 0xff;

return arr;
}

/** Convert raw 16 byte array to standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID. */
export function guidToStandardFormat(bufferSource: BufferSource) {
const arr =
bufferSource instanceof ArrayBuffer
? new Uint8Array(bufferSource)
: new Uint8Array(bufferSource.buffer);
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
const guid = (
byteToHex[arr[0]] +
byteToHex[arr[1]] +
byteToHex[arr[2]] +
byteToHex[arr[3]] +
"-" +
byteToHex[arr[4]] +
byteToHex[arr[5]] +
"-" +
byteToHex[arr[6]] +
byteToHex[arr[7]] +
"-" +
byteToHex[arr[8]] +
byteToHex[arr[9]] +
"-" +
byteToHex[arr[10]] +
byteToHex[arr[11]] +
byteToHex[arr[12]] +
byteToHex[arr[13]] +
byteToHex[arr[14]] +
byteToHex[arr[15]]
).toLowerCase();

// Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!Utils.isGuid(guid)) {
throw TypeError("Converted GUID is invalid");
}

return guid;
}

0 comments on commit 4ebf3ac

Please sign in to comment.