diff --git a/apps/browser/src/platform/browser/browser-api.ts b/apps/browser/src/platform/browser/browser-api.ts index 3801470993..bb195d9628 100644 --- a/apps/browser/src/platform/browser/browser-api.ts +++ b/apps/browser/src/platform/browser/browser-api.ts @@ -37,6 +37,10 @@ export class BrowserApi { ); } + static async removeWindow(windowId: number) { + await chrome.windows.remove(windowId); + } + static async getTabFromCurrentWindowId(): Promise | null { return await BrowserApi.tabsQueryFirst({ active: true, diff --git a/apps/browser/src/popup/services/popup-utils.service.ts b/apps/browser/src/popup/services/popup-utils.service.ts index b7ea330cdf..9d424586b2 100644 --- a/apps/browser/src/popup/services/popup-utils.service.ts +++ b/apps/browser/src/popup/services/popup-utils.service.ts @@ -55,69 +55,66 @@ export class PopupUtilsService { } } - popOut(win: Window, href: string = null, options: { center?: boolean } = {}): Promise { - return new Promise((resolve, reject) => { - if (href === null) { - href = win.location.href; - } + async popOut( + win: Window, + href: string = null, + options: { center?: boolean } = {} + ): Promise { + if (href === null) { + href = win.location.href; + } - if (typeof chrome !== "undefined" && chrome.windows && chrome.windows.create) { - if (href.indexOf("?uilocation=") > -1) { - href = href - .replace("uilocation=popup", "uilocation=popout") - .replace("uilocation=tab", "uilocation=popout") - .replace("uilocation=sidebar", "uilocation=popout"); - } else { - const hrefParts = href.split("#"); - href = - hrefParts[0] + "?uilocation=popout" + (hrefParts.length > 0 ? "#" + hrefParts[1] : ""); - } - - const bodyRect = document.querySelector("body").getBoundingClientRect(); - const width = Math.round(bodyRect.width ? bodyRect.width + 60 : 375); - const height = Math.round(bodyRect.height || 600); - const top = options.center ? Math.round((screen.height - height) / 2) : undefined; - const left = options.center ? Math.round((screen.width - width) / 2) : undefined; - chrome.windows.create( - { - url: href, - type: "popup", - width, - height, - top, - left, - }, - (window) => resolve({ type: "window", window }) - ); - - if (win && this.inPopup(win)) { - BrowserApi.closePopup(win); - } - } else if (typeof chrome !== "undefined" && chrome.tabs && chrome.tabs.create) { + if (chrome?.windows?.create != null) { + if (href.indexOf("?uilocation=") > -1) { href = href - .replace("uilocation=popup", "uilocation=tab") - .replace("uilocation=popout", "uilocation=tab") - .replace("uilocation=sidebar", "uilocation=tab"); - chrome.tabs.create( - { - url: href, - }, - (tab) => resolve({ type: "tab", tab }) - ); + .replace("uilocation=popup", "uilocation=popout") + .replace("uilocation=tab", "uilocation=popout") + .replace("uilocation=sidebar", "uilocation=popout"); } else { - reject(new Error("Cannot open tab or window")); + const hrefParts = href.split("#"); + href = + hrefParts[0] + "?uilocation=popout" + (hrefParts.length > 0 ? "#" + hrefParts[1] : ""); } - }); + + const bodyRect = document.querySelector("body").getBoundingClientRect(); + const width = Math.round(bodyRect.width ? bodyRect.width + 60 : 375); + const height = Math.round(bodyRect.height || 600); + const top = options.center ? Math.round((screen.height - height) / 2) : undefined; + const left = options.center ? Math.round((screen.width - width) / 2) : undefined; + const window = await BrowserApi.createWindow({ + url: href, + type: "popup", + width, + height, + top, + left, + }); + + if (win && this.inPopup(win)) { + BrowserApi.closePopup(win); + } + + return { type: "window", window }; + } else if (chrome?.tabs?.create != null) { + href = href + .replace("uilocation=popup", "uilocation=tab") + .replace("uilocation=popout", "uilocation=tab") + .replace("uilocation=sidebar", "uilocation=tab"); + + const tab = await BrowserApi.createNewTab(href); + return { type: "tab", tab }; + } else { + throw new Error("Cannot open tab or window"); + } } closePopOut(popout: Popout): Promise { - return new Promise((resolve) => { - if (popout.type === "window") { - chrome.windows.remove(popout.window.id, resolve); - } else { - chrome.tabs.remove(popout.tab.id, resolve); - } - }); + switch (popout.type) { + case "window": + return BrowserApi.removeWindow(popout.window.id); + case "tab": + return BrowserApi.removeTab(popout.tab.id); + } } /** diff --git a/apps/browser/src/vault/popup/components/action-buttons.component.html b/apps/browser/src/vault/popup/components/action-buttons.component.html index 97e41f2f5a..c1afffd508 100644 --- a/apps/browser/src/vault/popup/components/action-buttons.component.html +++ b/apps/browser/src/vault/popup/components/action-buttons.component.html @@ -120,9 +120,9 @@ appStopClick appStopProp appA11yTitle="{{ 'copyUsername' | i18n }}" - (click)="copy(cipher, cipher.fido2Key.userName, 'username', 'Username')" - [ngClass]="{ disabled: !cipher.fido2Key.userName }" - [attr.disabled]="!cipher.fido2Key.userName ? '' : null" + (click)="copy(cipher, cipher.fido2Key.userDisplayName, 'username', 'Username')" + [ngClass]="{ disabled: !cipher.fido2Key.userDisplayName }" + [attr.disabled]="!cipher.fido2Key.userDisplayName ? '' : null" > diff --git a/apps/browser/src/vault/popup/components/fido2/fido2.component.ts b/apps/browser/src/vault/popup/components/fido2/fido2.component.ts index 4aaba3b063..38c39ef906 100644 --- a/apps/browser/src/vault/popup/components/fido2/fido2.component.ts +++ b/apps/browser/src/vault/popup/components/fido2/fido2.component.ts @@ -86,7 +86,7 @@ export class Fido2Component implements OnInit, OnDestroy { cipher.name = message.credentialName; cipher.type = CipherType.Fido2Key; cipher.fido2Key = new Fido2KeyView(); - cipher.fido2Key.userName = message.userName; + cipher.fido2Key.userDisplayName = message.userName; this.ciphers = [cipher]; } else if (message.type === "PickCredentialRequest") { this.ciphers = await Promise.all( diff --git a/apps/browser/src/vault/popup/components/vault/add-edit.component.html b/apps/browser/src/vault/popup/components/vault/add-edit.component.html index 4033437e59..f88e2b8ee6 100644 --- a/apps/browser/src/vault/popup/components/vault/add-edit.component.html +++ b/apps/browser/src/vault/popup/components/vault/add-edit.component.html @@ -478,12 +478,12 @@
- + diff --git a/apps/browser/src/vault/popup/components/vault/view.component.html b/apps/browser/src/vault/popup/components/vault/view.component.html index b85d1473de..0748a23b8d 100644 --- a/apps/browser/src/vault/popup/components/vault/view.component.html +++ b/apps/browser/src/vault/popup/components/vault/view.component.html @@ -428,7 +428,7 @@
{{ "username" | i18n }} - {{ cipher.fido2Key.userName }} + {{ cipher.fido2Key.userDisplayName }}
{{ "typePasskey" | i18n }} diff --git a/apps/desktop/src/vault/app/vault/add-edit.component.html b/apps/desktop/src/vault/app/vault/add-edit.component.html index 4b6d1ed579..c81e2061c0 100644 --- a/apps/desktop/src/vault/app/vault/add-edit.component.html +++ b/apps/desktop/src/vault/app/vault/add-edit.component.html @@ -461,12 +461,12 @@
- + diff --git a/apps/desktop/src/vault/app/vault/view.component.html b/apps/desktop/src/vault/app/vault/view.component.html index c143583480..3a8e935758 100644 --- a/apps/desktop/src/vault/app/vault/view.component.html +++ b/apps/desktop/src/vault/app/vault/view.component.html @@ -399,7 +399,7 @@
{{ "username" | i18n }} - {{ cipher.fido2Key.userName }} + {{ cipher.fido2Key.userDisplayName }}
diff --git a/apps/web/src/app/vault/individual-vault/add-edit.component.html b/apps/web/src/app/vault/individual-vault/add-edit.component.html index 3e03423c8b..1d4d7522ac 100644 --- a/apps/web/src/app/vault/individual-vault/add-edit.component.html +++ b/apps/web/src/app/vault/individual-vault/add-edit.component.html @@ -836,14 +836,14 @@
- +
diff --git a/libs/angular/src/vault/vault-filter/models/vault-filter.model.ts b/libs/angular/src/vault/vault-filter/models/vault-filter.model.ts index cd5264c9e8..9b7f3282bd 100644 --- a/libs/angular/src/vault/vault-filter/models/vault-filter.model.ts +++ b/libs/angular/src/vault/vault-filter/models/vault-filter.model.ts @@ -45,7 +45,7 @@ export class VaultFilter { cipherPassesFilter = cipher.isDeleted; } if (this.cipherType != null && cipherPassesFilter) { - //Fido2Key's should also be included in the Login type + // Fido2Key's should also be included in the Login type if (this.cipherType === CipherType.Login) { cipherPassesFilter = cipher.type === this.cipherType || cipher.type === CipherType.Fido2Key; diff --git a/libs/common/src/models/export/fido2key.export.ts b/libs/common/src/models/export/fido2key.export.ts new file mode 100644 index 0000000000..6115016fae --- /dev/null +++ b/libs/common/src/models/export/fido2key.export.ts @@ -0,0 +1,91 @@ +import { EncString } from "../../platform/models/domain/enc-string"; +import { Fido2KeyView } from "../../vault/models/view/fido2-key.view"; + +import { Fido2Key as Fido2KeyDomain } from "./../../vault/models/domain/fido2-key"; + +export class Fido2KeyExport { + static template(): Fido2KeyExport { + const req = new Fido2KeyExport(); + req.credentialId = "keyId"; + req.keyType = "keyType"; + req.keyAlgorithm = "keyAlgorithm"; + req.keyCurve = "keyCurve"; + req.keyValue = "keyValue"; + req.rpId = "rpId"; + req.userHandle = "userHandle"; + req.counter = "counter"; + req.rpName = "rpName"; + req.userDisplayName = "userDisplayName"; + return req; + } + + static toView(req: Fido2KeyExport, view = new Fido2KeyView()) { + view.credentialId = req.credentialId; + view.keyType = req.keyType as "public-key"; + view.keyAlgorithm = req.keyAlgorithm as "ECDSA"; + view.keyCurve = req.keyCurve as "P-256"; + view.keyValue = req.keyValue; + view.rpId = req.rpId; + view.userHandle = req.userHandle; + view.counter = parseInt(req.counter); + view.rpName = req.rpName; + view.userDisplayName = req.userDisplayName; + return view; + } + + static toDomain(req: Fido2KeyExport, domain = new Fido2KeyDomain()) { + domain.credentialId = req.credentialId != null ? new EncString(req.credentialId) : null; + domain.keyType = req.keyType != null ? new EncString(req.keyType) : null; + domain.keyAlgorithm = req.keyAlgorithm != null ? new EncString(req.keyAlgorithm) : null; + domain.keyCurve = req.keyCurve != null ? new EncString(req.keyCurve) : null; + domain.keyValue = req.keyValue != null ? new EncString(req.keyValue) : null; + domain.rpId = req.rpId != null ? new EncString(req.rpId) : null; + domain.userHandle = req.userHandle != null ? new EncString(req.userHandle) : null; + domain.counter = req.counter != null ? new EncString(req.counter) : null; + domain.rpName = req.rpName != null ? new EncString(req.rpName) : null; + domain.userDisplayName = + req.userDisplayName != null ? new EncString(req.userDisplayName) : null; + return domain; + } + + credentialId: string; + keyType: string; + keyAlgorithm: string; + keyCurve: string; + keyValue: string; + rpId: string; + userHandle: string; + counter: string; + rpName: string; + userDisplayName: string; + + constructor(o?: Fido2KeyView | Fido2KeyDomain) { + if (o == null) { + return; + } + + if (o instanceof Fido2KeyView) { + this.credentialId = o.credentialId; + this.keyType = o.keyType; + this.keyAlgorithm = o.keyAlgorithm; + this.keyCurve = o.keyCurve; + this.keyValue = o.keyValue; + this.rpId = o.rpId; + this.userHandle = o.userHandle; + this.counter = String(o.counter); + this.rpName = o.rpName; + this.userDisplayName = o.userDisplayName; + } else { + this.credentialId = o.credentialId?.encryptedString; + this.keyType = o.keyType?.encryptedString; + this.keyAlgorithm = o.keyAlgorithm?.encryptedString; + this.keyCurve = o.keyCurve?.encryptedString; + this.keyValue = o.keyValue?.encryptedString; + this.rpId = o.rpId?.encryptedString; + this.userHandle = o.userHandle?.encryptedString; + this.counter = o.counter?.encryptedString; + this.rpName = o.rpName?.encryptedString; + this.userDisplayName = o.userDisplayName?.encryptedString; + } + } +} diff --git a/libs/common/src/models/export/login.export.ts b/libs/common/src/models/export/login.export.ts index 7a22b12537..0e26def1fe 100644 --- a/libs/common/src/models/export/login.export.ts +++ b/libs/common/src/models/export/login.export.ts @@ -2,6 +2,7 @@ import { EncString } from "../../platform/models/domain/enc-string"; import { Login as LoginDomain } from "../../vault/models/domain/login"; import { LoginView } from "../../vault/models/view/login.view"; +import { Fido2KeyExport } from "./fido2key.export"; import { LoginUriExport } from "./login-uri.export"; export class LoginExport { @@ -11,6 +12,7 @@ export class LoginExport { req.username = "jdoe"; req.password = "myp@ssword123"; req.totp = "JBSWY3DPEHPK3PXP"; + req.fido2Key = Fido2KeyExport.template(); return req; } @@ -21,6 +23,9 @@ export class LoginExport { view.username = req.username; view.password = req.password; view.totp = req.totp; + if (req.fido2Key != null) { + view.fido2Key = Fido2KeyExport.toView(req.fido2Key); + } return view; } @@ -31,6 +36,7 @@ export class LoginExport { domain.username = req.username != null ? new EncString(req.username) : null; domain.password = req.password != null ? new EncString(req.password) : null; domain.totp = req.totp != null ? new EncString(req.totp) : null; + //left out fido2Key for now return domain; } @@ -38,6 +44,7 @@ export class LoginExport { username: string; password: string; totp: string; + fido2Key: Fido2KeyExport = null; constructor(o?: LoginView | LoginDomain) { if (o == null) { @@ -52,6 +59,10 @@ export class LoginExport { } } + if (o.fido2Key != null) { + this.fido2Key = new Fido2KeyExport(o.fido2Key); + } + if (o instanceof LoginView) { this.username = o.username; this.password = o.password; diff --git a/libs/common/src/platform/misc/utils.ts b/libs/common/src/platform/misc/utils.ts index 2fb6f4f5a3..cd1b5fe33a 100644 --- a/libs/common/src/platform/misc/utils.ts +++ b/libs/common/src/platform/misc/utils.ts @@ -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; @@ -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 { @@ -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(); diff --git a/libs/common/src/vault/api/fido2-key.api.ts b/libs/common/src/vault/api/fido2-key.api.ts index 0673d3cd65..c98a06f1d1 100644 --- a/libs/common/src/vault/api/fido2-key.api.ts +++ b/libs/common/src/vault/api/fido2-key.api.ts @@ -1,7 +1,7 @@ import { BaseResponse } from "../../models/response/base.response"; export class Fido2KeyApi extends BaseResponse { - nonDiscoverableId: string; + credentialId: string; keyType: "public-key"; keyAlgorithm: "ECDSA"; keyCurve: "P-256"; @@ -9,10 +9,8 @@ export class Fido2KeyApi extends BaseResponse { rpId: string; userHandle: string; counter: string; - - // Extras rpName: string; - userName: string; + userDisplayName: string; constructor(data: any = null) { super(data); @@ -20,7 +18,7 @@ export class Fido2KeyApi extends BaseResponse { return; } - this.nonDiscoverableId = this.getResponseProperty("NonDiscoverableId"); + this.credentialId = this.getResponseProperty("CredentialId"); this.keyType = this.getResponseProperty("KeyType"); this.keyAlgorithm = this.getResponseProperty("KeyAlgorithm"); this.keyCurve = this.getResponseProperty("KeyCurve"); @@ -29,6 +27,6 @@ export class Fido2KeyApi extends BaseResponse { this.userHandle = this.getResponseProperty("UserHandle"); this.counter = this.getResponseProperty("Counter"); this.rpName = this.getResponseProperty("RpName"); - this.userName = this.getResponseProperty("UserName"); + this.userDisplayName = this.getResponseProperty("UserDisplayName"); } } diff --git a/libs/common/src/vault/models/data/fido2-key.data.ts b/libs/common/src/vault/models/data/fido2-key.data.ts index b73cc2f70b..45d2feadf4 100644 --- a/libs/common/src/vault/models/data/fido2-key.data.ts +++ b/libs/common/src/vault/models/data/fido2-key.data.ts @@ -1,7 +1,7 @@ import { Fido2KeyApi } from "../../api/fido2-key.api"; export class Fido2KeyData { - nonDiscoverableId: string; + credentialId: string; keyType: "public-key"; keyAlgorithm: "ECDSA"; keyCurve: "P-256"; @@ -9,17 +9,15 @@ export class Fido2KeyData { rpId: string; userHandle: string; counter: string; - - // Extras rpName: string; - userName: string; + userDisplayName: string; constructor(data?: Fido2KeyApi) { if (data == null) { return; } - this.nonDiscoverableId = data.nonDiscoverableId; + this.credentialId = data.credentialId; this.keyType = data.keyType; this.keyAlgorithm = data.keyAlgorithm; this.keyCurve = data.keyCurve; @@ -28,6 +26,6 @@ export class Fido2KeyData { this.userHandle = data.userHandle; this.counter = data.counter; this.rpName = data.rpName; - this.userName = data.userName; + this.userDisplayName = data.userDisplayName; } } diff --git a/libs/common/src/vault/models/domain/fido2-key.spec.ts b/libs/common/src/vault/models/domain/fido2-key.spec.ts new file mode 100644 index 0000000000..6804963fbe --- /dev/null +++ b/libs/common/src/vault/models/domain/fido2-key.spec.ts @@ -0,0 +1,147 @@ +import { mockEnc } from "../../../../spec"; +import { EncryptionType } from "../../../enums"; +import { EncString } from "../../../platform/models/domain/enc-string"; +import { Fido2KeyData } from "../data/fido2-key.data"; + +import { Fido2Key } from "./fido2-key"; + +describe("Fido2Key", () => { + describe("constructor", () => { + it("returns all fields null when given empty data parameter", () => { + const data = new Fido2KeyData(); + const fido2Key = new Fido2Key(data); + + expect(fido2Key).toEqual({ + credentialId: null, + keyType: null, + keyAlgorithm: null, + keyCurve: null, + keyValue: null, + rpId: null, + userHandle: null, + rpName: null, + userDisplayName: null, + counter: null, + }); + }); + + it("returns all fields as EncStrings when given full Fido2KeyData", () => { + const data: Fido2KeyData = { + credentialId: "credentialId", + keyType: "public-key", + keyAlgorithm: "ECDSA", + keyCurve: "P-256", + keyValue: "keyValue", + rpId: "rpId", + userHandle: "userHandle", + counter: "counter", + rpName: "rpName", + userDisplayName: "userDisplayName", + }; + const fido2Key = new Fido2Key(data); + + expect(fido2Key).toEqual({ + credentialId: { encryptedString: "credentialId", encryptionType: 0 }, + keyType: { encryptedString: "public-key", encryptionType: 0 }, + keyAlgorithm: { encryptedString: "ECDSA", encryptionType: 0 }, + keyCurve: { encryptedString: "P-256", encryptionType: 0 }, + keyValue: { encryptedString: "keyValue", encryptionType: 0 }, + rpId: { encryptedString: "rpId", encryptionType: 0 }, + userHandle: { encryptedString: "userHandle", encryptionType: 0 }, + counter: { encryptedString: "counter", encryptionType: 0 }, + rpName: { encryptedString: "rpName", encryptionType: 0 }, + userDisplayName: { encryptedString: "userDisplayName", encryptionType: 0 }, + }); + }); + + it("should not populate fields when data parameter is not given", () => { + const fido2Key = new Fido2Key(); + + expect(fido2Key).toEqual({ + credentialId: null, + }); + }); + }); + + describe("decrypt", () => { + it("decrypts and populates all fields when populated with EncStrings", async () => { + const fido2Key = new Fido2Key(); + fido2Key.credentialId = mockEnc("credentialId"); + fido2Key.keyType = mockEnc("keyType"); + fido2Key.keyAlgorithm = mockEnc("keyAlgorithm"); + fido2Key.keyCurve = mockEnc("keyCurve"); + fido2Key.keyValue = mockEnc("keyValue"); + fido2Key.rpId = mockEnc("rpId"); + fido2Key.userHandle = mockEnc("userHandle"); + fido2Key.counter = mockEnc("2"); + fido2Key.rpName = mockEnc("rpName"); + fido2Key.userDisplayName = mockEnc("userDisplayName"); + + const fido2KeyView = await fido2Key.decrypt(null); + + expect(fido2KeyView).toEqual({ + credentialId: "credentialId", + keyType: "keyType", + keyAlgorithm: "keyAlgorithm", + keyCurve: "keyCurve", + keyValue: "keyValue", + rpId: "rpId", + userHandle: "userHandle", + rpName: "rpName", + userDisplayName: "userDisplayName", + counter: 2, + }); + }); + }); + + describe("toFido2KeyData", () => { + it("encodes to data object when converted from Fido2KeyData and back", () => { + const data: Fido2KeyData = { + credentialId: "credentialId", + keyType: "public-key", + keyAlgorithm: "ECDSA", + keyCurve: "P-256", + keyValue: "keyValue", + rpId: "rpId", + userHandle: "userHandle", + counter: "counter", + rpName: "rpName", + userDisplayName: "userDisplayName", + }; + + const fido2Key = new Fido2Key(data); + const result = fido2Key.toFido2KeyData(); + + expect(result).toEqual(data); + }); + }); + + describe("fromJSON", () => { + it("recreates equivalent object when converted to JSON and back", () => { + const fido2Key = new Fido2Key(); + fido2Key.credentialId = createEncryptedEncString("credentialId"); + fido2Key.keyType = createEncryptedEncString("keyType"); + fido2Key.keyAlgorithm = createEncryptedEncString("keyAlgorithm"); + fido2Key.keyCurve = createEncryptedEncString("keyCurve"); + fido2Key.keyValue = createEncryptedEncString("keyValue"); + fido2Key.rpId = createEncryptedEncString("rpId"); + fido2Key.userHandle = createEncryptedEncString("userHandle"); + fido2Key.counter = createEncryptedEncString("2"); + fido2Key.rpName = createEncryptedEncString("rpName"); + fido2Key.userDisplayName = createEncryptedEncString("userDisplayName"); + + const json = JSON.stringify(fido2Key); + const result = Fido2Key.fromJSON(JSON.parse(json)); + + expect(result).toEqual(fido2Key); + }); + + it("returns null if input is null", () => { + expect(Fido2Key.fromJSON(null)).toBeNull(); + }); + }); +}); + +function createEncryptedEncString(s: string): EncString { + return new EncString(`${EncryptionType.AesCbc256_HmacSha256_B64}.${s}`); +} diff --git a/libs/common/src/vault/models/domain/fido2-key.ts b/libs/common/src/vault/models/domain/fido2-key.ts index 21820ae6ce..e03920f3d6 100644 --- a/libs/common/src/vault/models/domain/fido2-key.ts +++ b/libs/common/src/vault/models/domain/fido2-key.ts @@ -7,7 +7,7 @@ import { Fido2KeyData } from "../data/fido2-key.data"; import { Fido2KeyView } from "../view/fido2-key.view"; export class Fido2Key extends Domain { - nonDiscoverableId: EncString | null = null; + credentialId: EncString | null = null; keyType: EncString; keyAlgorithm: EncString; keyCurve: EncString; @@ -15,11 +15,8 @@ export class Fido2Key extends Domain { rpId: EncString; userHandle: EncString; counter: EncString; - - // Extras rpName: EncString; - userName: EncString; - origin: EncString; + userDisplayName: EncString; constructor(obj?: Fido2KeyData) { super(); @@ -31,7 +28,7 @@ export class Fido2Key extends Domain { this, obj, { - nonDiscoverableId: null, + credentialId: null, keyType: null, keyAlgorithm: null, keyCurve: null, @@ -40,8 +37,7 @@ export class Fido2Key extends Domain { userHandle: null, counter: null, rpName: null, - userName: null, - origin: null, + userDisplayName: null, }, [] ); @@ -51,7 +47,7 @@ export class Fido2Key extends Domain { const view = await this.decryptObj( new Fido2KeyView(), { - nonDiscoverableId: null, + credentialId: null, keyType: null, keyAlgorithm: null, keyCurve: null, @@ -59,8 +55,7 @@ export class Fido2Key extends Domain { rpId: null, userHandle: null, rpName: null, - userName: null, - origin: null, + userDisplayName: null, }, orgId, encKey @@ -83,7 +78,7 @@ export class Fido2Key extends Domain { toFido2KeyData(): Fido2KeyData { const i = new Fido2KeyData(); this.buildDataModel(this, i, { - nonDiscoverableId: null, + credentialId: null, keyType: null, keyAlgorithm: null, keyCurve: null, @@ -92,8 +87,7 @@ export class Fido2Key extends Domain { userHandle: null, counter: null, rpName: null, - userName: null, - origin: null, + userDisplayName: null, }); return i; } @@ -103,7 +97,7 @@ export class Fido2Key extends Domain { return null; } - const nonDiscoverableId = EncString.fromJSON(obj.nonDiscoverableId); + const credentialId = EncString.fromJSON(obj.credentialId); const keyType = EncString.fromJSON(obj.keyType); const keyAlgorithm = EncString.fromJSON(obj.keyAlgorithm); const keyCurve = EncString.fromJSON(obj.keyCurve); @@ -112,11 +106,10 @@ export class Fido2Key extends Domain { const userHandle = EncString.fromJSON(obj.userHandle); const counter = EncString.fromJSON(obj.counter); const rpName = EncString.fromJSON(obj.rpName); - const userName = EncString.fromJSON(obj.userName); - const origin = EncString.fromJSON(obj.origin); + const userDisplayName = EncString.fromJSON(obj.userDisplayName); return Object.assign(new Fido2Key(), obj, { - nonDiscoverableId, + credentialId, keyType, keyAlgorithm, keyCurve, @@ -125,8 +118,7 @@ export class Fido2Key extends Domain { userHandle, counter, rpName, - userName, - origin, + userDisplayName, }); } } diff --git a/libs/common/src/vault/models/domain/login.spec.ts b/libs/common/src/vault/models/domain/login.spec.ts index 6a4f5ba3c9..30b3077cb3 100644 --- a/libs/common/src/vault/models/domain/login.spec.ts +++ b/libs/common/src/vault/models/domain/login.spec.ts @@ -113,7 +113,7 @@ describe("Login DTO", () => { passwordRevisionDate: passwordRevisionDate.toISOString(), totp: "myTotp" as EncryptedString, fido2Key: { - nonDiscoverableId: "keyId" as EncryptedString, + credentialId: "keyId" as EncryptedString, keyType: "keyType" as EncryptedString, keyAlgorithm: "keyAlgorithm" as EncryptedString, keyCurve: "keyCurve" as EncryptedString, @@ -122,8 +122,7 @@ describe("Login DTO", () => { userHandle: "userHandle" as EncryptedString, counter: "counter" as EncryptedString, rpName: "rpName" as EncryptedString, - userName: "userName" as EncryptedString, - origin: "origin" as EncryptedString, + userDisplayName: "userDisplayName" as EncryptedString, }, }); @@ -134,7 +133,7 @@ describe("Login DTO", () => { passwordRevisionDate: passwordRevisionDate, totp: "myTotp_fromJSON", fido2Key: { - nonDiscoverableId: "keyId_fromJSON", + credentialId: "keyId_fromJSON", keyType: "keyType_fromJSON", keyAlgorithm: "keyAlgorithm_fromJSON", keyCurve: "keyCurve_fromJSON", @@ -143,8 +142,7 @@ describe("Login DTO", () => { userHandle: "userHandle_fromJSON", counter: "counter_fromJSON", rpName: "rpName_fromJSON", - userName: "userName_fromJSON", - origin: "origin_fromJSON", + userDisplayName: "userDisplayName_fromJSON", }, }); expect(actual).toBeInstanceOf(Login); diff --git a/libs/common/src/vault/models/request/cipher.request.ts b/libs/common/src/vault/models/request/cipher.request.ts index 17b75f5daf..5ca6cfc781 100644 --- a/libs/common/src/vault/models/request/cipher.request.ts +++ b/libs/common/src/vault/models/request/cipher.request.ts @@ -66,9 +66,9 @@ export class CipherRequest { if (cipher.login.fido2Key != null) { this.login.fido2Key = new Fido2KeyApi(); - this.login.fido2Key.nonDiscoverableId = - cipher.login.fido2Key.nonDiscoverableId != null - ? cipher.login.fido2Key.nonDiscoverableId.encryptedString + this.login.fido2Key.credentialId = + cipher.login.fido2Key.credentialId != null + ? cipher.login.fido2Key.credentialId.encryptedString : null; this.login.fido2Key.keyType = cipher.login.fido2Key.keyType != null @@ -100,9 +100,9 @@ export class CipherRequest { cipher.login.fido2Key.userHandle != null ? cipher.login.fido2Key.userHandle.encryptedString : null; - this.login.fido2Key.userName = - cipher.login.fido2Key.userName != null - ? cipher.login.fido2Key.userName.encryptedString + this.login.fido2Key.userDisplayName = + cipher.login.fido2Key.userDisplayName != null + ? cipher.login.fido2Key.userDisplayName.encryptedString : null; } break; @@ -167,9 +167,9 @@ export class CipherRequest { break; case CipherType.Fido2Key: this.fido2Key = new Fido2KeyApi(); - this.fido2Key.nonDiscoverableId = - cipher.fido2Key.nonDiscoverableId != null - ? cipher.fido2Key.nonDiscoverableId.encryptedString + this.fido2Key.credentialId = + cipher.fido2Key.credentialId != null + ? cipher.fido2Key.credentialId.encryptedString : null; this.fido2Key.keyType = cipher.fido2Key.keyType != null @@ -193,8 +193,10 @@ export class CipherRequest { cipher.fido2Key.counter != null ? cipher.fido2Key.counter.encryptedString : null; this.fido2Key.userHandle = cipher.fido2Key.userHandle != null ? cipher.fido2Key.userHandle.encryptedString : null; - this.fido2Key.userName = - cipher.fido2Key.userName != null ? cipher.fido2Key.userName.encryptedString : null; + this.fido2Key.userDisplayName = + cipher.fido2Key.userDisplayName != null + ? cipher.fido2Key.userDisplayName.encryptedString + : null; break; default: break; diff --git a/libs/common/src/vault/models/view/fido2-key.view.ts b/libs/common/src/vault/models/view/fido2-key.view.ts index 9644feff6e..6fec5dbf25 100644 --- a/libs/common/src/vault/models/view/fido2-key.view.ts +++ b/libs/common/src/vault/models/view/fido2-key.view.ts @@ -3,7 +3,7 @@ import { Jsonify } from "type-fest"; import { ItemView } from "./item.view"; export class Fido2KeyView extends ItemView { - nonDiscoverableId: string; + credentialId: string; keyType: "public-key"; keyAlgorithm: "ECDSA"; keyCurve: "P-256"; @@ -11,13 +11,11 @@ export class Fido2KeyView extends ItemView { rpId: string; userHandle: string; counter: number; - - // Extras rpName: string; - userName: string; + userDisplayName: string; get subTitle(): string { - return this.userName; + return this.userDisplayName; } get canLaunch(): boolean { diff --git a/libs/common/src/vault/models/view/login.view.ts b/libs/common/src/vault/models/view/login.view.ts index 16fee10721..86284151a3 100644 --- a/libs/common/src/vault/models/view/login.view.ts +++ b/libs/common/src/vault/models/view/login.view.ts @@ -84,7 +84,7 @@ export class LoginView extends ItemView { const fido2Key = obj.fido2Key == null ? null : Fido2KeyView.fromJSON(obj.fido2Key); return Object.assign(new LoginView(), obj, { - passwordRevisionDate: passwordRevisionDate, + passwordRevisionDate, uris, fido2Key, }); diff --git a/libs/common/src/vault/services/cipher.service.ts b/libs/common/src/vault/services/cipher.service.ts index e307066f69..907095041b 100644 --- a/libs/common/src/vault/services/cipher.service.ts +++ b/libs/common/src/vault/services/cipher.service.ts @@ -1095,7 +1095,7 @@ export class CipherService implements CipherServiceAbstraction { model.login.fido2Key, cipher.login.fido2Key, { - nonDiscoverableId: null, + credentialId: null, keyType: null, keyAlgorithm: null, keyCurve: null, @@ -1103,7 +1103,7 @@ export class CipherService implements CipherServiceAbstraction { rpId: null, rpName: null, userHandle: null, - userName: null, + userDisplayName: null, origin: null, }, key @@ -1168,6 +1168,7 @@ export class CipherService implements CipherServiceAbstraction { model.fido2Key, cipher.fido2Key, { + credentialId: null, keyType: null, keyAlgorithm: null, keyCurve: null, @@ -1175,7 +1176,7 @@ export class CipherService implements CipherServiceAbstraction { rpId: null, rpName: null, userHandle: null, - userName: null, + userDisplayName: null, origin: null, }, key diff --git a/libs/common/src/vault/services/fido2/cbor.ts b/libs/common/src/vault/services/fido2/cbor.ts new file mode 100644 index 0000000000..b74822fd4b --- /dev/null +++ b/libs/common/src/vault/services/fido2/cbor.ts @@ -0,0 +1,494 @@ +/** +The MIT License (MIT) + +Copyright (c) 2014-2016 Patrick Gansterer +Copyright (c) 2020-present Aaron Huggins + +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. + +Exported from GitHub release version 0.4.0 +*/ + +/* eslint-disable */ +/** @hidden */ +const POW_2_24 = 5.960464477539063e-8; +/** @hidden */ +const POW_2_32 = 4294967296; +/** @hidden */ +const POW_2_53 = 9007199254740992; +/** @hidden */ +const DECODE_CHUNK_SIZE = 8192; + +/** @hidden */ +function objectIs(x: any, y: any) { + if (typeof Object.is === "function") return Object.is(x, y); + + // SameValue algorithm + // Steps 1-5, 7-10 + if (x === y) { + // Steps 6.b-6.e: +0 != -0 + return x !== 0 || 1 / x === 1 / y; + } + + // Step 6.a: NaN == NaN + return x !== x && y !== y; +} + +/** A function that extracts tagged values. */ +type TaggedValueFunction = (value: any, tag: number) => TaggedValue; +/** A function that extracts simple values. */ +type SimpleValueFunction = (value: any) => SimpleValue; + +/** Convenience class for structuring a tagged value. */ +export class TaggedValue { + constructor(value: any, tag: number) { + this.value = value; + this.tag = tag; + } + + value: any; + tag: number; +} + +/** Convenience class for structuring a simple value. */ +export class SimpleValue { + constructor(value: any) { + this.value = value; + } + + value: any; +} + +/** + * Converts a Concise Binary Object Representation (CBOR) buffer into an object. + * @param {ArrayBuffer|SharedArrayBuffer} data - A valid CBOR buffer. + * @param {Function} [tagger] - A function that extracts tagged values. This function is called for each member of the object. + * @param {Function} [simpleValue] - A function that extracts simple values. This function is called for each member of the object. + * @returns {any} The CBOR buffer converted to a JavaScript value. + */ +export function decode( + data: ArrayBuffer | SharedArrayBuffer, + tagger?: TaggedValueFunction, + simpleValue?: SimpleValueFunction +): T { + let dataView = new DataView(data); + let ta = new Uint8Array(data); + let offset = 0; + let tagValueFunction: TaggedValueFunction = function (value: number, tag: number): any { + return new TaggedValue(value, tag); + }; + let simpleValFunction: SimpleValueFunction = function (value: number): SimpleValue { + return undefined as unknown as SimpleValue; + }; + + if (typeof tagger === "function") tagValueFunction = tagger; + if (typeof simpleValue === "function") simpleValFunction = simpleValue; + + function commitRead(length: number, value: T): T { + offset += length; + return value; + } + function readArrayBuffer(length: number) { + return commitRead(length, new Uint8Array(data, offset, length)); + } + function readFloat16() { + let tempArrayBuffer = new ArrayBuffer(4); + let tempDataView = new DataView(tempArrayBuffer); + let value = readUint16(); + + let sign = value & 0x8000; + let exponent = value & 0x7c00; + let fraction = value & 0x03ff; + + if (exponent === 0x7c00) exponent = 0xff << 10; + else if (exponent !== 0) exponent += (127 - 15) << 10; + else if (fraction !== 0) return (sign ? -1 : 1) * fraction * POW_2_24; + + tempDataView.setUint32(0, (sign << 16) | (exponent << 13) | (fraction << 13)); + return tempDataView.getFloat32(0); + } + function readFloat32(): number { + return commitRead(4, dataView.getFloat32(offset)); + } + function readFloat64(): number { + return commitRead(8, dataView.getFloat64(offset)); + } + function readUint8(): number { + return commitRead(1, ta[offset]); + } + function readUint16(): number { + return commitRead(2, dataView.getUint16(offset)); + } + function readUint32(): number { + return commitRead(4, dataView.getUint32(offset)); + } + function readUint64(): number { + return readUint32() * POW_2_32 + readUint32(); + } + function readBreak(): boolean { + if (ta[offset] !== 0xff) return false; + offset += 1; + return true; + } + function readLength(additionalInformation: number): number { + if (additionalInformation < 24) return additionalInformation; + if (additionalInformation === 24) return readUint8(); + if (additionalInformation === 25) return readUint16(); + if (additionalInformation === 26) return readUint32(); + if (additionalInformation === 27) return readUint64(); + if (additionalInformation === 31) return -1; + throw new Error("Invalid length encoding"); + } + function readIndefiniteStringLength(majorType: number): number { + let initialByte = readUint8(); + if (initialByte === 0xff) return -1; + let length = readLength(initialByte & 0x1f); + if (length < 0 || initialByte >> 5 !== majorType) + throw new Error("Invalid indefinite length element"); + return length; + } + + function appendUtf16Data(utf16data: number[], length: number) { + for (let i = 0; i < length; ++i) { + let value = readUint8(); + if (value & 0x80) { + if (value < 0xe0) { + value = ((value & 0x1f) << 6) | (readUint8() & 0x3f); + length -= 1; + } else if (value < 0xf0) { + value = ((value & 0x0f) << 12) | ((readUint8() & 0x3f) << 6) | (readUint8() & 0x3f); + length -= 2; + } else { + value = + ((value & 0x0f) << 18) | + ((readUint8() & 0x3f) << 12) | + ((readUint8() & 0x3f) << 6) | + (readUint8() & 0x3f); + length -= 3; + } + } + + if (value < 0x10000) { + utf16data.push(value); + } else { + value -= 0x10000; + utf16data.push(0xd800 | (value >> 10)); + utf16data.push(0xdc00 | (value & 0x3ff)); + } + } + } + + function decodeItem(): any { + let initialByte = readUint8(); + let majorType = initialByte >> 5; + let additionalInformation = initialByte & 0x1f; + let i; + let length; + + if (majorType === 7) { + switch (additionalInformation) { + case 25: + return readFloat16(); + case 26: + return readFloat32(); + case 27: + return readFloat64(); + } + } + + length = readLength(additionalInformation); + if (length < 0 && (majorType < 2 || 6 < majorType)) throw new Error("Invalid length"); + + switch (majorType) { + case 0: + return length; + case 1: + return -1 - length; + case 2: + if (length < 0) { + let elements = []; + let fullArrayLength = 0; + while ((length = readIndefiniteStringLength(majorType)) >= 0) { + fullArrayLength += length; + elements.push(readArrayBuffer(length)); + } + let fullArray = new Uint8Array(fullArrayLength); + let fullArrayOffset = 0; + for (i = 0; i < elements.length; ++i) { + fullArray.set(elements[i], fullArrayOffset); + fullArrayOffset += elements[i].length; + } + return fullArray; + } + return readArrayBuffer(length); + case 3: + let utf16data: number[] = []; + if (length < 0) { + while ((length = readIndefiniteStringLength(majorType)) >= 0) + appendUtf16Data(utf16data, length); + } else { + appendUtf16Data(utf16data, length); + } + let string = ""; + for (i = 0; i < utf16data.length; i += DECODE_CHUNK_SIZE) { + string += String.fromCharCode.apply(null, utf16data.slice(i, i + DECODE_CHUNK_SIZE)); + } + return string; + case 4: + let retArray; + if (length < 0) { + retArray = []; + while (!readBreak()) retArray.push(decodeItem()); + } else { + retArray = new Array(length); + for (i = 0; i < length; ++i) retArray[i] = decodeItem(); + } + return retArray; + case 5: + let retObject: any = {}; + for (i = 0; i < length || (length < 0 && !readBreak()); ++i) { + let key = decodeItem(); + retObject[key] = decodeItem(); + } + return retObject; + case 6: + return tagValueFunction(decodeItem(), length); + case 7: + switch (length) { + case 20: + return false; + case 21: + return true; + case 22: + return null; + case 23: + return undefined; + default: + return simpleValFunction(length); + } + } + } + + let ret = decodeItem(); + if (offset !== data.byteLength) throw new Error("Remaining bytes"); + return ret; +} + +/** + * Converts a JavaScript value to a Concise Binary Object Representation (CBOR) buffer. + * @param {any} value - A JavaScript value, usually an object or array, to be converted. + * @returns {ArrayBuffer} The JavaScript value converted to CBOR format. + */ +export function encode(value: T): ArrayBuffer { + let data = new ArrayBuffer(256); + let dataView = new DataView(data); + let byteView = new Uint8Array(data); + let lastLength: number; + let offset = 0; + + function prepareWrite(length: number): DataView { + let newByteLength = data.byteLength; + let requiredLength = offset + length; + while (newByteLength < requiredLength) newByteLength <<= 1; + if (newByteLength !== data.byteLength) { + let oldDataView = dataView; + data = new ArrayBuffer(newByteLength); + dataView = new DataView(data); + byteView = new Uint8Array(data); + let uint32count = (offset + 3) >> 2; + for (let i = 0; i < uint32count; ++i) + dataView.setUint32(i << 2, oldDataView.getUint32(i << 2)); + } + + lastLength = length; + return dataView; + } + function commitWrite(...args: any[]) { + offset += lastLength; + } + function writeFloat64(val: number) { + commitWrite(prepareWrite(8).setFloat64(offset, val)); + } + function writeUint8(val: number) { + commitWrite(prepareWrite(1).setUint8(offset, val)); + } + function writeUint8Array(val: number[] | Uint8Array) { + prepareWrite(val.length); + byteView.set(val, offset); + commitWrite(); + } + function writeUint16(val: number) { + commitWrite(prepareWrite(2).setUint16(offset, val)); + } + function writeUint32(val: number) { + commitWrite(prepareWrite(4).setUint32(offset, val)); + } + function writeUint64(val: number) { + let low = val % POW_2_32; + let high = (val - low) / POW_2_32; + let view = prepareWrite(8); + view.setUint32(offset, high); + view.setUint32(offset + 4, low); + commitWrite(); + } + function writeVarUint(val: number, mod: number = 0) { + if (val <= 0xff) { + if (val < 24) { + writeUint8(val | mod); + } else { + writeUint8(0x18 | mod); + writeUint8(val); + } + } else if (val <= 0xffff) { + writeUint8(0x19 | mod); + writeUint16(val); + } else if (val <= 0xffffffff) { + writeUint8(0x1a | mod); + writeUint32(val); + } else { + writeUint8(0x1b | mod); + writeUint64(val); + } + } + function writeTypeAndLength(type: number, length: number) { + if (length < 24) { + writeUint8((type << 5) | length); + } else if (length < 0x100) { + writeUint8((type << 5) | 24); + writeUint8(length); + } else if (length < 0x10000) { + writeUint8((type << 5) | 25); + writeUint16(length); + } else if (length < 0x100000000) { + writeUint8((type << 5) | 26); + writeUint32(length); + } else { + writeUint8((type << 5) | 27); + writeUint64(length); + } + } + + function encodeItem(val: any) { + let i; + + if (val === false) return writeUint8(0xf4); + if (val === true) return writeUint8(0xf5); + if (val === null) return writeUint8(0xf6); + if (val === undefined) return writeUint8(0xf7); + if (objectIs(val, -0)) return writeUint8Array([0xf9, 0x80, 0x00]); + + switch (typeof val) { + case "number": + if (Math.floor(val) === val) { + if (0 <= val && val <= POW_2_53) return writeTypeAndLength(0, val); + if (-POW_2_53 <= val && val < 0) return writeTypeAndLength(1, -(val + 1)); + } + writeUint8(0xfb); + return writeFloat64(val); + + case "string": + let utf8data = []; + for (i = 0; i < val.length; ++i) { + let charCode = val.charCodeAt(i); + if (charCode < 0x80) { + utf8data.push(charCode); + } else if (charCode < 0x800) { + utf8data.push(0xc0 | (charCode >> 6)); + utf8data.push(0x80 | (charCode & 0x3f)); + } else if (charCode < 0xd800 || charCode >= 0xe000) { + utf8data.push(0xe0 | (charCode >> 12)); + utf8data.push(0x80 | ((charCode >> 6) & 0x3f)); + utf8data.push(0x80 | (charCode & 0x3f)); + } else { + charCode = (charCode & 0x3ff) << 10; + charCode |= val.charCodeAt(++i) & 0x3ff; + charCode += 0x10000; + + utf8data.push(0xf0 | (charCode >> 18)); + utf8data.push(0x80 | ((charCode >> 12) & 0x3f)); + utf8data.push(0x80 | ((charCode >> 6) & 0x3f)); + utf8data.push(0x80 | (charCode & 0x3f)); + } + } + + writeTypeAndLength(3, utf8data.length); + return writeUint8Array(utf8data); + + default: + let length; + let converted; + if (Array.isArray(val)) { + length = val.length; + writeTypeAndLength(4, length); + for (i = 0; i < length; i += 1) encodeItem(val[i]); + } else if (val instanceof Uint8Array) { + writeTypeAndLength(2, val.length); + writeUint8Array(val); + } else if (ArrayBuffer.isView(val)) { + converted = new Uint8Array(val.buffer); + writeTypeAndLength(2, converted.length); + writeUint8Array(converted); + } else if ( + val instanceof ArrayBuffer || + (typeof SharedArrayBuffer === "function" && val instanceof SharedArrayBuffer) + ) { + converted = new Uint8Array(val); + writeTypeAndLength(2, converted.length); + writeUint8Array(converted); + } else if (val instanceof TaggedValue) { + writeVarUint(val.tag, 0b11000000); + encodeItem(val.value); + } else { + let keys = Object.keys(val); + length = keys.length; + writeTypeAndLength(5, length); + for (i = 0; i < length; i += 1) { + let key = keys[i]; + encodeItem(key); + encodeItem(val[key]); + } + } + } + } + + encodeItem(value); + + if ("slice" in data) return data.slice(0, offset); + + let ret = new ArrayBuffer(offset); + let retView = new DataView(ret); + for (let i = 0; i < offset; ++i) retView.setUint8(i, dataView.getUint8(i)); + return ret; +} + +/** + * An intrinsic object that provides functions to convert JavaScript values + * to and from the Concise Binary Object Representation (CBOR) format. + */ +export const CBOR: { + decode: ( + data: ArrayBuffer | SharedArrayBuffer, + tagger?: TaggedValueFunction, + simpleValue?: SimpleValueFunction + ) => T; + encode: (value: T) => ArrayBuffer; +} = { + decode, + encode, +}; diff --git a/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts b/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts index 82a65f2a0f..76b209d225 100644 --- a/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts +++ b/libs/common/src/vault/services/fido2/fido2-authenticator.service.spec.ts @@ -1,6 +1,5 @@ import { TextEncoder } from "util"; -import { CBOR } from "cbor-redux"; import { mock, MockProxy } from "jest-mock-extended"; import { Utils } from "../../../platform/misc/utils"; @@ -22,8 +21,10 @@ import { CipherView } from "../../models/view/cipher.view"; import { Fido2KeyView } from "../../models/view/fido2-key.view"; import { LoginView } from "../../models/view/login.view"; +import { CBOR } from "./cbor"; import { AAGUID, Fido2AuthenticatorService } from "./fido2-authenticator.service"; import { Fido2Utils } from "./fido2-utils"; +import { guidToRawFormat } from "./guid-utils"; const RpId = "bitwarden.com"; @@ -110,12 +111,12 @@ describe("FidoAuthenticatorService", () => { beforeEach(async () => { excludedCipher = createCipherView( { type: CipherType.Login }, - { nonDiscoverableId: Utils.newGuid() } + { credentialId: Utils.newGuid() } ); params = await createParams({ excludeCredentialDescriptorList: [ { - id: Utils.guidToRawFormat(excludedCipher.login.fido2Key.nonDiscoverableId), + id: guidToRawFormat(excludedCipher.login.fido2Key.credentialId), type: "public-key", }, ], @@ -189,7 +190,10 @@ describe("FidoAuthenticatorService", () => { excludedCipherView = createCipherView(); params = await createParams({ excludeCredentialDescriptorList: [ - { id: Utils.guidToRawFormat(excludedCipherView.id), type: "public-key" }, + { + id: guidToRawFormat(excludedCipherView.fido2Key.credentialId), + type: "public-key", + }, ], }); cipherService.get.mockImplementation(async (id) => @@ -315,7 +319,7 @@ describe("FidoAuthenticatorService", () => { name: params.rpEntity.name, fido2Key: expect.objectContaining({ - nonDiscoverableId: null, + credentialId: expect.anything(), keyType: "public-key", keyAlgorithm: "ECDSA", keyCurve: "P-256", @@ -323,7 +327,7 @@ describe("FidoAuthenticatorService", () => { rpName: params.rpEntity.name, userHandle: Fido2Utils.bufferToString(params.userEntity.id), counter: 0, - userName: params.userEntity.displayName, + userDisplayName: params.userEntity.displayName, }), }) ); @@ -414,7 +418,7 @@ describe("FidoAuthenticatorService", () => { login: expect.objectContaining({ fido2Key: expect.objectContaining({ - nonDiscoverableId: expect.anything(), + credentialId: expect.anything(), keyType: "public-key", keyAlgorithm: "ECDSA", keyCurve: "P-256", @@ -422,7 +426,7 @@ describe("FidoAuthenticatorService", () => { rpName: params.rpEntity.name, userHandle: Fido2Utils.bufferToString(params.userEntity.id), counter: 0, - userName: params.userEntity.displayName, + userDisplayName: params.userEntity.displayName, }), }), }) @@ -464,12 +468,8 @@ describe("FidoAuthenticatorService", () => { requireResidentKey ? "discoverable" : "non-discoverable" } credential`, () => { const cipherId = "75280e7e-a72e-4d6c-bf1e-d37238352f9b"; - const cipherIdBytes = new Uint8Array([ - 0x75, 0x28, 0x0e, 0x7e, 0xa7, 0x2e, 0x4d, 0x6c, 0xbf, 0x1e, 0xd3, 0x72, 0x38, 0x35, 0x2f, - 0x9b, - ]); - const nonDiscoverableId = "52217b91-73f1-4fea-b3f2-54a7959fd5aa"; - const nonDiscoverableIdBytes = new Uint8Array([ + const credentialId = "52217b91-73f1-4fea-b3f2-54a7959fd5aa"; + const credentialIdBytes = new Uint8Array([ 0x52, 0x21, 0x7b, 0x91, 0x73, 0xf1, 0x4f, 0xea, 0xb3, 0xf2, 0x54, 0xa7, 0x95, 0x9f, 0xd5, 0xaa, ]); @@ -492,7 +492,9 @@ describe("FidoAuthenticatorService", () => { cipherService.getAllDecrypted.mockResolvedValue([await cipher]); cipherService.encrypt.mockImplementation(async (cipher) => { if (!requireResidentKey) { - cipher.login.fido2Key.nonDiscoverableId = nonDiscoverableId; // Replace id for testability + cipher.login.fido2Key.credentialId = credentialId; // Replace id for testability + } else { + cipher.fido2Key.credentialId = credentialId; } return {} as any; }); @@ -537,11 +539,7 @@ describe("FidoAuthenticatorService", () => { expect(counter).toEqual(new Uint8Array([0, 0, 0, 0])); // 0 because of new counter expect(aaguid).toEqual(AAGUID); expect(credentialIdLength).toEqual(new Uint8Array([0, 16])); // 16 bytes because we're using GUIDs - if (requireResidentKey) { - expect(credentialId).toEqual(cipherIdBytes); - } else { - expect(credentialId).toEqual(nonDiscoverableIdBytes); - } + expect(credentialId).toEqual(credentialIdBytes); }); }); } @@ -636,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, }); @@ -660,7 +658,7 @@ describe("FidoAuthenticatorService", () => { it("should inform user if credential exists but rpId does not match", async () => { const cipher = await createCipherView({ type: CipherType.Login }); - cipher.login.fido2Key.nonDiscoverableId = credentialId; + cipher.login.fido2Key.credentialId = credentialId; cipher.login.fido2Key.rpId = "mismatch-rpid"; cipherService.getAllDecrypted.mockResolvedValue([cipher]); userInterfaceSession.informCredentialNotFound.mockResolvedValue(); @@ -703,16 +701,16 @@ describe("FidoAuthenticatorService", () => { ciphers = [ await createCipherView( { type: CipherType.Login }, - { nonDiscoverableId: credentialIds[0], rpId: RpId } + { credentialId: credentialIds[0], rpId: RpId } ), await createCipherView( - { type: CipherType.Fido2Key, id: credentialIds[1] }, - { rpId: RpId } + { type: CipherType.Fido2Key }, + { credentialId: credentialIds[1], rpId: RpId } ), ]; params = await createParams({ allowCredentialDescriptorList: credentialIds.map((credentialId) => ({ - id: Utils.guidToRawFormat(credentialId), + id: guidToRawFormat(credentialId), type: "public-key", })), rpId: RpId, @@ -772,11 +770,11 @@ describe("FidoAuthenticatorService", () => { ciphers = credentialIds.map((id) => createCipherView( { type: CipherType.Fido2Key }, - { rpId: RpId, counter: 9000, keyValue } + { credentialId: id, rpId: RpId, counter: 9000, keyValue } ) ); fido2Keys = ciphers.map((c) => c.fido2Key); - selectedCredentialId = ciphers[0].id; + selectedCredentialId = credentialIds[0]; params = await createParams({ allowCredentialDescriptorList: undefined, rpId: RpId, @@ -785,14 +783,14 @@ describe("FidoAuthenticatorService", () => { ciphers = credentialIds.map((id) => createCipherView( { type: CipherType.Login }, - { nonDiscoverableId: id, rpId: RpId, counter: 9000 } + { credentialId: id, rpId: RpId, counter: 9000 } ) ); fido2Keys = ciphers.map((c) => c.login.fido2Key); selectedCredentialId = credentialIds[0]; params = await createParams({ allowCredentialDescriptorList: credentialIds.map((credentialId) => ({ - id: Utils.guidToRawFormat(credentialId), + id: guidToRawFormat(credentialId), type: "public-key", })), rpId: RpId, @@ -845,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) ); @@ -940,7 +938,7 @@ function createCipherView( cipher.localData = {}; const fido2KeyView = new Fido2KeyView(); - fido2KeyView.nonDiscoverableId = fido2Key.nonDiscoverableId; + fido2KeyView.credentialId = fido2Key.credentialId ?? Utils.newGuid(); fido2KeyView.rpId = fido2Key.rpId ?? RpId; fido2KeyView.counter = fido2Key.counter ?? 0; fido2KeyView.userHandle = fido2Key.userHandle ?? Fido2Utils.bufferToString(randomBytes(16)); diff --git a/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts b/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts index 29e8d628b6..eb69ad5ff1 100644 --- a/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts +++ b/libs/common/src/vault/services/fido2/fido2-authenticator.service.ts @@ -1,5 +1,3 @@ -import { CBOR } from "cbor-redux"; - import { LogService } from "../../../platform/abstractions/log.service"; import { Utils } from "../../../platform/misc/utils"; import { CipherService } from "../../abstractions/cipher.service"; @@ -20,8 +18,10 @@ import { CipherType } from "../../enums/cipher-type"; import { CipherView } from "../../models/view/cipher.view"; import { Fido2KeyView } from "../../models/view/fido2-key.view"; +import { CBOR } from "./cbor"; 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([ @@ -101,6 +101,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr let fido2Key: Fido2KeyView; let keyPair: CryptoKeyPair; let userVerified = false; + let credentialId: string; if (params.requireResidentKey) { const response = await userInterfaceSession.confirmNewCredential( { @@ -137,6 +138,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr const encrypted = await this.cipherService.encrypt(cipher); await this.cipherService.createWithServer(encrypted); // encrypted.id is assigned inside here cipher.id = encrypted.id; + credentialId = cipher.fido2Key.credentialId; } catch (error) { this.logService?.error( `[Fido2Authenticator] Aborting because of unknown error when creating discoverable credential: ${error}` @@ -177,6 +179,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr cipher.login.fido2Key = fido2Key = await createKeyView(params, keyPair.privateKey); const reencrypted = await this.cipherService.encrypt(cipher); await this.cipherService.updateWithServer(reencrypted); + credentialId = cipher.login.fido2Key.credentialId; } catch (error) { this.logService?.error( `[Fido2Authenticator] Aborting because of unknown error when creating non-discoverable credential: ${error}` @@ -185,12 +188,9 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr } } - const credentialId = - cipher.type === CipherType.Fido2Key ? cipher.id : cipher.login.fido2Key.nonDiscoverableId; - const authData = await generateAuthData({ rpId: params.rpEntity.id, - credentialId: Utils.guidToRawFormat(credentialId), + credentialId: guidToRawFormat(credentialId), counter: fido2Key.counter, userPresence: true, userVerification: userVerified, @@ -205,7 +205,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr ); return { - credentialId: Utils.guidToRawFormat(credentialId), + credentialId: guidToRawFormat(credentialId), attestationObject, authData, publicKeyAlgorithm: -7, @@ -286,10 +286,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr selectedCipher.type === CipherType.Login ? selectedCipher.login.fido2Key : selectedCipher.fido2Key; - const selectedCredentialId = - selectedCipher.type === CipherType.Login - ? selectedFido2Key.nonDiscoverableId - : selectedCipher.id; + const selectedCredentialId = selectedFido2Key.credentialId; ++selectedFido2Key.counter; @@ -302,7 +299,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, @@ -317,7 +314,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr return { authenticatorData, selectedCredential: { - id: Utils.guidToRawFormat(selectedCredentialId), + id: guidToRawFormat(selectedCredentialId), userHandle: Fido2Utils.stringToBuffer(selectedFido2Key.userHandle), }, signature, @@ -341,7 +338,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 {} } @@ -361,10 +358,10 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr (cipher) => !cipher.isDeleted && cipher.organizationId == undefined && - ((cipher.type === CipherType.Fido2Key && ids.includes(cipher.id)) || + ((cipher.type === CipherType.Fido2Key && ids.includes(cipher.fido2Key.credentialId)) || (cipher.type === CipherType.Login && cipher.login.fido2Key != undefined && - ids.includes(cipher.login.fido2Key.nonDiscoverableId))) + ids.includes(cipher.login.fido2Key.credentialId))) ) .map((cipher) => cipher.id); } @@ -377,7 +374,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 {} } @@ -398,10 +395,10 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr cipher.type === CipherType.Login && cipher.login.fido2Key != undefined && cipher.login.fido2Key.rpId === rpId && - ids.includes(cipher.login.fido2Key.nonDiscoverableId)) || + ids.includes(cipher.login.fido2Key.credentialId)) || (cipher.type === CipherType.Fido2Key && cipher.fido2Key.rpId === rpId && - ids.includes(cipher.id)) + ids.includes(cipher.fido2Key.credentialId)) ); } @@ -440,7 +437,7 @@ async function createKeyView( const pkcs8Key = await crypto.subtle.exportKey("pkcs8", keyValue); const fido2Key = new Fido2KeyView(); - fido2Key.nonDiscoverableId = params.requireResidentKey ? null : Utils.newGuid(); + fido2Key.credentialId = Utils.newGuid(); fido2Key.keyType = "public-key"; fido2Key.keyAlgorithm = "ECDSA"; fido2Key.keyCurve = "P-256"; @@ -449,7 +446,7 @@ async function createKeyView( fido2Key.userHandle = Fido2Utils.bufferToString(params.userEntity.id); fido2Key.counter = 0; fido2Key.rpName = params.rpEntity.name; - fido2Key.userName = params.userEntity.displayName; + fido2Key.userDisplayName = params.userEntity.displayName; return fido2Key; } diff --git a/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts b/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts index a22091625f..8f8141df9c 100644 --- a/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts +++ b/libs/common/src/vault/services/fido2/fido2-client.service.spec.ts @@ -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"; @@ -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, @@ -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({ diff --git a/libs/common/src/vault/services/fido2/guid-utils.ts b/libs/common/src/vault/services/fido2/guid-utils.ts new file mode 100644 index 0000000000..66e6cbb1d7 --- /dev/null +++ b/libs/common/src/vault/services/fido2/guid-utils.ts @@ -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; +} diff --git a/package.json b/package.json index db08080181..d067344124 100644 --- a/package.json +++ b/package.json @@ -168,7 +168,6 @@ "bootstrap": "4.6.0", "braintree-web-drop-in": "1.40.0", "bufferutil": "4.0.7", - "cbor-redux": "^0.4.0", "chalk": "4.1.2", "commander": "7.2.0", "core-js": "3.32.0",