From 86a5d5607cd373b5090ccbb18aa075f30f938250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20=C3=85berg?= Date: Mon, 10 Nov 2025 19:05:11 +0100 Subject: [PATCH] Beta: Windows Native passkey provider Co-Authored-By: Isaiah Inuwa Co-Authored-By: Colton Hurst --- .github/CODEOWNERS | 2 + .github/workflows/build-desktop.yml | 30 +- .../autofill/popup/fido2/fido2.component.ts | 15 +- apps/browser/store/windows/AppxManifest.xml | 7 + apps/desktop/.vscode/launch.json | 20 +- apps/desktop/build.ps1 | 27 + apps/desktop/com.bitwarden.pfx | Bin 0 -> 2694 bytes apps/desktop/custom-appx-manifest.xml | 127 ++ apps/desktop/desktop_native/Cargo.lock | 1583 ++++++++++++----- apps/desktop/desktop_native/Cargo.toml | 6 +- apps/desktop/desktop_native/build.js | 9 +- apps/desktop/desktop_native/core/Cargo.toml | 2 + .../desktop_native/core/src/autofill/mod.rs | 122 ++ .../core/src/autofill/windows.rs | 625 ++++++- .../core/src/biometric/windows.rs | 4 +- .../desktop_native/macos_provider/README.md | 35 + .../desktop_native/macos_provider/build.sh | 3 + .../desktop_native/macos_provider/src/lib.rs | 83 +- .../macos_provider/src/registration.rs | 1 + apps/desktop/desktop_native/napi/Cargo.toml | 1 + apps/desktop/desktop_native/napi/index.d.ts | 11 +- apps/desktop/desktop_native/napi/src/lib.rs | 35 +- .../passkey_authenticator_internal/dummy.rs | 24 + .../objc/src/native/autofill/commands/sync.m | 82 +- .../desktop_native/objc/src/native/utils.m | 19 +- .../desktop_native/rust-toolchain.toml | 2 +- .../windows_plugin_authenticator/Cargo.toml | 11 + .../include/pluginauthenticator.h | 263 +++ .../include/pluginauthenticator.idl | 83 + .../include/webauthn.h | 1381 ++++++++++++++ .../include/webauthnplugin.h | 588 ++++++ .../src/assert.rs | 424 +++++ .../src/com_buffer.rs | 84 + .../src/com_provider.rs | 229 +++ .../src/com_registration.rs | 338 ++++ .../src/ipc2/assertion.rs | 57 + .../src/ipc2/mod.rs | 369 ++++ .../src/ipc2/registration.rs | 44 + .../windows_plugin_authenticator/src/lib.rs | 182 +- .../src/make_credential.rs | 769 ++++++++ .../src/pluginauthenticator.rs | 110 -- .../windows_plugin_authenticator/src/types.rs | 35 + .../windows_plugin_authenticator/src/util.rs | 102 ++ .../src/webauthn.rs | 423 ++++- apps/desktop/electron-builder.beta.json | 5 +- apps/desktop/electron-builder.json | 8 +- .../CredentialProviderViewController.xib | 87 +- .../CredentialProviderViewController.swift | 381 ++-- .../macos/autofill-extension/Info.plist | 4 +- .../autofill_extension.entitlements | 8 +- .../autofill-extension/bitwarden-icon.png | Bin 0 -> 3291 bytes .../en.lproj/Localizable.strings | 2 + .../macos/desktop.xcodeproj/project.pbxproj | 25 + apps/desktop/package.json | 22 +- apps/desktop/resources/entitlements.mac.plist | 2 - .../resources/entitlements.mas.inherit.plist | 4 +- apps/desktop/resources/entitlements.mas.plist | 12 +- apps/desktop/sign.js | 55 +- apps/desktop/sign.ps1 | Bin 0 -> 166 bytes apps/desktop/src/app/app-routing.module.ts | 19 +- apps/desktop/src/app/app.component.ts | 3 +- .../components/fido2placeholder.component.ts | 122 -- .../src/app/services/services.module.ts | 1 + .../autofill/guards/reactive-vault-guard.ts | 42 + .../credentials/fido2-create.component.html | 66 + .../fido2-create.component.spec.ts | 238 +++ .../credentials/fido2-create.component.ts | 219 +++ .../fido2-excluded-ciphers.component.html | 44 + .../fido2-excluded-ciphers.component.spec.ts | 78 + .../fido2-excluded-ciphers.component.ts | 78 + .../credentials/fido2-vault.component.html | 37 + .../credentials/fido2-vault.component.spec.ts | 196 ++ .../credentials/fido2-vault.component.ts | 161 ++ apps/desktop/src/autofill/preload.ts | 21 + .../services/desktop-autofill.service.ts | 280 ++- .../desktop-fido2-user-interface.service.ts | 159 +- apps/desktop/src/locales/en/messages.json | 77 +- apps/desktop/src/main.ts | 7 +- apps/desktop/src/main/tray.main.ts | 11 +- apps/desktop/src/main/window.main.ts | 6 +- .../main/autofill/native-autofill.main.ts | 83 +- .../platform/models/domain/window-state.ts | 1 + .../src/platform/popup-modal-styles.ts | 14 +- .../services/desktop-settings.service.ts | 7 +- .../services/electron-log.main.service.ts | 2 +- build.sh | 8 + eslint.config.mjs | 3 +- libs/common/spec/fake-account-service.ts | 7 + .../src/auth/abstractions/account.service.ts | 7 + .../src/auth/services/account.service.spec.ts | 10 + .../src/auth/services/account.service.ts | 7 + libs/common/src/enums/feature-flag.enum.ts | 2 + ...fido2-authenticator.service.abstraction.ts | 2 +- ...ido2-user-interface.service.abstraction.ts | 2 +- .../fido2/fido2-authenticator.service.ts | 5 +- .../services/fido2/fido2-utils.spec.ts | 64 + .../platform/services/fido2/fido2-utils.ts | 14 + .../services/fido2/guid-utils.spec.ts | 73 +- .../src/platform/services/fido2/guid-utils.ts | 4 + .../src/vault/abstractions/cipher.service.ts | 1 + .../src/vault/services/cipher.service.ts | 9 + libs/components/src/icon-button/index.ts | 2 +- libs/components/src/tw-theme.css | 12 + .../lock/components/lock.component.spec.ts | 72 +- .../src/lock/components/lock.component.ts | 11 +- package-lock.json | 61 - 106 files changed, 9933 insertions(+), 1397 deletions(-) create mode 100644 apps/desktop/build.ps1 create mode 100644 apps/desktop/com.bitwarden.pfx create mode 100644 apps/desktop/custom-appx-manifest.xml create mode 100644 apps/desktop/desktop_native/macos_provider/README.md create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.h create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.idl create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthn.h create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthnplugin.h create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/assert.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/com_buffer.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/com_provider.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/com_registration.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/assertion.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/mod.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/registration.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/make_credential.rs delete mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/pluginauthenticator.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/types.rs create mode 100644 apps/desktop/desktop_native/windows_plugin_authenticator/src/util.rs create mode 100644 apps/desktop/macos/autofill-extension/bitwarden-icon.png create mode 100644 apps/desktop/macos/autofill-extension/en.lproj/Localizable.strings create mode 100644 apps/desktop/sign.ps1 delete mode 100644 apps/desktop/src/app/components/fido2placeholder.component.ts create mode 100644 apps/desktop/src/autofill/guards/reactive-vault-guard.ts create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-create.component.html create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-create.component.spec.ts create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-create.component.ts create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.html create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.spec.ts create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.ts create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-vault.component.html create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-vault.component.spec.ts create mode 100644 apps/desktop/src/autofill/modal/credentials/fido2-vault.component.ts create mode 100644 build.sh diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 39e968d941b..d372a39b1e7 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -8,7 +8,9 @@ apps/desktop/desktop_native @bitwarden/team-platform-dev apps/desktop/desktop_native/objc/src/native/autofill @bitwarden/team-autofill-desktop-dev apps/desktop/desktop_native/core/src/autofill @bitwarden/team-autofill-desktop-dev +apps/desktop/desktop_native/macos_provider @bitwarden/team-autofill-desktop-dev apps/desktop/desktop_native/core/src/secure_memory @bitwarden/team-key-management-dev + ## No ownership for Cargo.lock and Cargo.toml to allow dependency updates apps/desktop/desktop_native/Cargo.lock apps/desktop/desktop_native/Cargo.toml diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index 39549c4580c..70ed55c08c4 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -908,7 +908,7 @@ jobs: macos-build: name: MacOS Build - runs-on: macos-13 + runs-on: macos-15 needs: - setup permissions: @@ -935,8 +935,13 @@ jobs: cache-dependency-path: '**/package-lock.json' node-version: ${{ env._NODE_VERSION }} + - name: Set up Python + uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 + with: + python-version: '3.13' + - name: Set up Node-gyp - run: python3 -m pip install setuptools + run: python -m pip install setuptools - name: Print environment run: | @@ -945,6 +950,7 @@ jobs: rustup show echo "GitHub ref: $GITHUB_REF" echo "GitHub event: $GITHUB_EVENT" + xcodebuild -showsdks - name: Cache Build id: build-cache @@ -1132,7 +1138,7 @@ jobs: macos-package-github: name: MacOS Package GitHub Release Assets - runs-on: macos-13 + runs-on: macos-15 if: ${{ needs.setup.outputs.has_secrets == 'true' }} needs: - browser-build @@ -1162,8 +1168,13 @@ jobs: cache-dependency-path: '**/package-lock.json' node-version: ${{ env._NODE_VERSION }} + - name: Set up Python + uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 + with: + python-version: '3.13' + - name: Set up Node-gyp - run: python3 -m pip install setuptools + run: python -m pip install setuptools - name: Print environment run: | @@ -1172,6 +1183,7 @@ jobs: rustup show echo "GitHub ref: $GITHUB_REF" echo "GitHub event: $GITHUB_EVENT" + xcodebuild -showsdks - name: Get Build Cache id: build-cache @@ -1393,7 +1405,7 @@ jobs: macos-package-mas: name: MacOS Package Prod Release Asset - runs-on: macos-13 + runs-on: macos-15 if: ${{ needs.setup.outputs.has_secrets == 'true' }} needs: - browser-build @@ -1423,8 +1435,13 @@ jobs: cache-dependency-path: '**/package-lock.json' node-version: ${{ env._NODE_VERSION }} + - name: Set up Python + uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 + with: + python-version: '3.13' + - name: Set up Node-gyp - run: python3 -m pip install setuptools + run: python -m pip install setuptools - name: Print environment run: | @@ -1433,6 +1450,7 @@ jobs: rustup show echo "GitHub ref: $GITHUB_REF" echo "GitHub event: $GITHUB_EVENT" + xcodebuild -showsdks - name: Get Build Cache id: build-cache diff --git a/apps/browser/src/autofill/popup/fido2/fido2.component.ts b/apps/browser/src/autofill/popup/fido2/fido2.component.ts index c6799f93a5e..c1982d27d24 100644 --- a/apps/browser/src/autofill/popup/fido2/fido2.component.ts +++ b/apps/browser/src/autofill/popup/fido2/fido2.component.ts @@ -24,6 +24,7 @@ import { getUserId } from "@bitwarden/common/auth/services/account.service"; import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { Fido2Utils } from "@bitwarden/common/platform/services/fido2/fido2-utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { SearchService } from "@bitwarden/common/vault/abstractions/search.service"; import { SecureNoteType, CipherType } from "@bitwarden/common/vault/enums"; @@ -198,7 +199,7 @@ export class Fido2Component implements OnInit, OnDestroy { this.displayedCiphers = this.ciphers.filter( (cipher) => cipher.login.matchesUri(this.url, equivalentDomains) && - this.cipherHasNoOtherPasskeys(cipher, message.userHandle), + Fido2Utils.cipherHasNoOtherPasskeys(cipher, message.userHandle), ); this.passkeyAction = PasskeyActions.Register; @@ -472,16 +473,4 @@ export class Fido2Component implements OnInit, OnDestroy { ...msg, }); } - - /** - * This methods returns true if a cipher either has no passkeys, or has a passkey matching with userHandle - * @param userHandle - */ - private cipherHasNoOtherPasskeys(cipher: CipherView, userHandle: string): boolean { - if (cipher.login.fido2Credentials == null || cipher.login.fido2Credentials.length === 0) { - return true; - } - - return cipher.login.fido2Credentials.some((passkey) => passkey.userHandle === userHandle); - } } diff --git a/apps/browser/store/windows/AppxManifest.xml b/apps/browser/store/windows/AppxManifest.xml index 9765506a558..2063534f62e 100644 --- a/apps/browser/store/windows/AppxManifest.xml +++ b/apps/browser/store/windows/AppxManifest.xml @@ -44,6 +44,13 @@ DisplayName="Bitwarden Password Manager"> + + + + + + + diff --git a/apps/desktop/.vscode/launch.json b/apps/desktop/.vscode/launch.json index 66c1161be46..e3fa1088c0d 100644 --- a/apps/desktop/.vscode/launch.json +++ b/apps/desktop/.vscode/launch.json @@ -6,11 +6,25 @@ "type": "node", "request": "launch", "cwd": "${workspaceRoot}/build", - "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron", + "runtimeExecutable": "${workspaceRoot}/../../node_modules/.bin/electron", "windows": { - "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron.cmd" + "runtimeExecutable": "${workspaceRoot}/../../node_modules/.bin/electron.cmd" }, - "args": ["."] + "args": [".", "--remote-debugging-port=9223"] + }, + { + "name": "Debug Renderer Process", + "type": "chrome", + "request": "attach", + "port": 9223, + "webRoot": "${workspaceFolder}", + "timeout": 30000 + } + ], + "compounds": [ + { + "name": "Debug Electron: All", + "configurations": ["Debug Main Process", "Debug Renderer Process"] } ] } diff --git a/apps/desktop/build.ps1 b/apps/desktop/build.ps1 new file mode 100644 index 00000000000..cbec6782882 --- /dev/null +++ b/apps/desktop/build.ps1 @@ -0,0 +1,27 @@ +$ErrorActionPreference = "Stop" +$PSNativeCommandUseErrorActionPreference = $true + +$env:ELECTRON_BUILDER_SIGN_CERT = "C:\temp\code-signing.pfx" +$env:ELECTRON_BUILDER_SIGN_CERT_PW = "1234" +$bwFolder = "$env:LOCALAPPDATA\Packages\bitwardendesktop_h4e712dmw3xyy" + +$package = (Get-AppxPackage -name bitwardendesktop) +$appx = ".\dist\Bitwarden-2025.10.2-arm64.appx" +$backupDataFile = "C:\temp\bw-data.json" +$comLogFile = "C:\temp\bitwarden_com_debug.log" + +# Build Appx +npm run build-native && npm run build:dev && npm run pack:win:arm64 + +# Backup tokens +# Copy-Item -Path "$bwFolder\LocalCache\Roaming\Bitwarden\data.json" -Destination $backupDataFile + +# Reinstall Appx +Remove-AppxPackage $package && Add-AppxPackage $appx + +# Delete log files +Remove-Item -Path $comLogFile + +# Restore tokens +# New-Item -Type Directory -Force -Path "$bwFolder\LocalCache\Roaming\Bitwarden\" +# Copy-Item -Path $backupDataFile -Destination "$bwFolder\LocalCache\Roaming\Bitwarden\data.json" diff --git a/apps/desktop/com.bitwarden.pfx b/apps/desktop/com.bitwarden.pfx new file mode 100644 index 0000000000000000000000000000000000000000..ed82d494b20d3de2562a053abe7f04b7d4e00e8f GIT binary patch literal 2694 zcmZXUc{r5)9>$-U#>j+>ZDi-QHMSY+2!jaWZ5vB8_K9qR8CfbzlPy#tORq9x*T`0u zA!JF^K{6Ftk}Yf5!=TR8^`7@!=Q@A{2@ku;8_UqrE-389%(T-&##)Qzw@UMQ{mkdCV8P zNOxkm5Ab?2x)=gNpo}0p+JTG6)v05u_k9(@w8Mc9rgR&$4@U`%00oMd|o~> ziX1(H=gl&{`~BOeOzAHakp7bSlO+a2MKMjO9-B3BC(e`bg;1EgH`**ZFsFFKAiObE zmJF#1P?=rrSuV_kzZ1!=oHaVOAd=%?65%6fA@fKyw|&><~# zI72}B;(AlL*vI59uhWW&F=spa=bsPDy3k*%93!fjMNs(#;GK`}PpuM*@8++T5hR_k zt&KjLr}s<_zc4yeu)-@jGNh(-$NEC0&Q4CT+Lh74{X83M-&iKEzt+x$CI3|>s{O%L zpVU>w7bj%5>arCscLhmn(*WszQD;wfjCttI(R?vw(?4a8$8nUs6V0NLq6 z_MbViq8DfBL1ROY-s~;Oy96gOSv>fhXtT~3V7Fe{$MMhg`KcLQ62f&kD>x6HFO04!D=k9Khw%jfV0e3Z+z9JTJ z?HqBa5!Naa_sXn2zJXDeKW;A#H+{n4gU!t`N@6ZEUR;U?j=_$}lc&e_W zlDWmgEnYlH#fTY)`wu+tmC~JgVchA{6A-XzTS5LB{zFw6IoA_#;@lRbccsJi0?#ST zys?B;dY$1B$SYRiS9-B~iwNS#O%?P#Llj5A27?(Uh4`yNp@1@`LRYd33KDiBb_v+$ zPUFCF9RP8)ziP$Mr^Mly= z1IqeK#+d*YJfvePk@xjU>SryU)Kva=vwDGtJN@n$YnBG7l*b^qX&eili1n!*D39u8 z3c5yVJ2CNMf(9((gNi}Shoq>N-RoN&@K2|zevm^Y$Ite-hKD?>Z}{%SG}?DGPS=e0 zJ@+;tSD;6Cc+^voGTE(a7~fDS5!Mm7foonOWqc+2^79}gmNcw9p57h_=3s`ER!f!L z{G&P6Ppe*F4}qw2M_*^61pcW@E+I4&0s#R4fO7sX6hxnqJOzXR7XeiO4QK%bz!T5} zG}zOfO$dPAZ>Gwgnt&I8VKWS%%ieX_8;X7Fu$5mvP4@db>=ZQM`72%-3W9(rx^U3% z_&)(3b|47|1jy{;#r~W$fctw3V;f0qqcmX6o)N#55Vl5QbMN2$%x`BXJA=S}Cb2tR z>YxATgtBX%kBzv&Ab@>w{8s_}fAQazC}HTkg@ybo{us)EAybx=Fj1|Q+HWc{_=qt) zPWrgn9vvAjzC0HnymbwAx!(wA&+wtgmW^C>>Cy{#71*E6uP!C74c!TH>g;y{jdQ7F z0Hb@Kxz9RMiY8SKym!9LJ4+K_x*CRH-gsBuzs{MzVY*y_EG#NM8AX3}q|eRaoTlMb zPbSZKu`eSE52dYEhk9z1jT(DlvQC;w-c{K2JWTBIM&EAjznr*cG#zx~TLXVu7;B4B zH9|b%;vUH?XvylXKqE!*`lOnDN1T|q`)<5XD*CEp1?O9uD&C`{y|{n{UKB2F*2AFr zYq&cH;_K7f=y4jwxc0-JoDrBo*hlY&;C?#8$@Qncl(n!+Q&)e@Piw1BM$c!w@yZu+ zrrJ&PCou2N7^<^Ky+;<$`)Avty9>o>NRg-*n^T)r6~+vmEY>2@$%G^!-r}m`48eVD z9w3M6!rz_Al`Cj-uStQ;w+RW_9IK=`e8uYoC8)af_%&S0eI%Vo}`!ZKa$e|1hzI;Bi zsx^_m6myMK`*gPUg!|#81l>}YAk?FNJ9M2Kh5&xmag|s zxNEV=Dj(nf;Jz2kxsxa4Qpb8(%%$Kg=R;;30M!!auqUN2d5eiZdbF1YW{}q@^RPa_ zR;@EUVU?Mz)hBtg0jaH_G48RgwGP1+U*p2ZI9jhOdXJ@a!z5J?Kc2WvMELTb(n^ji zw#ln&_-r6^fEB#Tq2DLx=X*jM|8xf{zM?*A^f^0XV9iNcV_4|*a8hB#Tv5sZzQ})C zcdB_I%f<<8U&5Wf5|AfAA`?zFXV%=X+aa_PykkS{1HDRY<7LzNtQpR?eG|pI + + + + + + + ${displayName} + ${publisherDisplayName} + A secure and free password manager for all of your devices. + assets\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${displayName} + + + + + + + + + + + + + \ No newline at end of file diff --git a/apps/desktop/desktop_native/Cargo.lock b/apps/desktop/desktop_native/Cargo.lock index cf635f39df3..e45955de069 100644 --- a/apps/desktop/desktop_native/Cargo.lock +++ b/apps/desktop/desktop_native/Cargo.lock @@ -4,18 +4,18 @@ version = 4 [[package]] name = "addr2line" -version = "0.24.2" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" dependencies = [ "gimli", ] [[package]] name = "adler2" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aead" @@ -55,18 +55,18 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" dependencies = [ "memchr", ] [[package]] name = "anstream" -version = "0.6.18" +version = "0.6.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" dependencies = [ "anstyle", "anstyle-parse", @@ -79,37 +79,37 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.10" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" [[package]] name = "anstyle-parse" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.2" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] name = "anstyle-wincon" -version = "3.0.7" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" +checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" dependencies = [ "anstyle", - "once_cell", - "windows-sys 0.59.0", + "once_cell_polyfill", + "windows-sys 0.60.2", ] [[package]] @@ -207,9 +207,9 @@ dependencies = [ [[package]] name = "async-channel" -version = "2.3.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b47800b0be77592da0afd425cc03468052844aff33b84e33cc696f64e77b6a" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" dependencies = [ "concurrent-queue", "event-listener-strategy", @@ -219,9 +219,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.13.2" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb812ffb58524bdd10860d7d974e2f01cc0950c2438a74ee5ec2e2280c6c4ffa" +checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8" dependencies = [ "async-task", "concurrent-queue", @@ -233,28 +233,27 @@ dependencies = [ [[package]] name = "async-io" -version = "2.4.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a2b323ccce0a1d90b449fd71f2a06ca7faa7c54c2751f06c9bd851fc061059" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" dependencies = [ - "async-lock", + "autocfg", "cfg-if", "concurrent-queue", "futures-io", "futures-lite", "parking", "polling", - "rustix 0.38.44", + "rustix 1.1.2", "slab", - "tracing", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] name = "async-lock" -version = "3.4.0" +version = "3.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" +checksum = "5fd03604047cee9b6ce9de9f70c6cd540a0520c813cbd49bae61f33ab80ed1dc" dependencies = [ "event-listener", "event-listener-strategy", @@ -263,9 +262,9 @@ dependencies = [ [[package]] name = "async-process" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63255f1dc2381611000436537bbedfe83183faa303a5a0edaf191edef06526bb" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" dependencies = [ "async-channel", "async-io", @@ -276,8 +275,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 0.38.44", - "tracing", + "rustix 1.1.2", ] [[package]] @@ -293,9 +291,9 @@ dependencies = [ [[package]] name = "async-signal" -version = "0.2.10" +version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "637e00349800c0bdf8bfc21ebbc0b6524abea702b0da4168ac00d070d0c0b9f3" +checksum = "43c070bbf59cd3570b6b2dd54cd772527c7c3620fce8be898406dd3ed6adc64c" dependencies = [ "async-io", "async-lock", @@ -303,10 +301,10 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 0.38.44", + "rustix 1.1.2", "signal-hook-registry", "slab", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -334,9 +332,9 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] name = "autocfg" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "autotype" @@ -346,15 +344,15 @@ dependencies = [ "mockall", "serial_test", "tracing", - "windows 0.61.1", - "windows-core 0.61.0", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] name = "backtrace" -version = "0.3.75" +version = "0.3.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" dependencies = [ "addr2line", "cfg-if", @@ -362,7 +360,7 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets 0.52.6", + "windows-link 0.2.1", ] [[package]] @@ -379,9 +377,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "base64ct" -version = "1.7.3" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89e25b6adfb930f02d1981565a6e5d9c547ac15a96606256d3b59040e5cd4ca3" +checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" [[package]] name = "basic-toml" @@ -414,9 +412,9 @@ dependencies = [ [[package]] name = "bitflags" -version = "2.9.0" +version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" [[package]] name = "bitwarden-russh" @@ -454,8 +452,7 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", - "verifysign", - "windows 0.61.1", + "windows 0.62.2", ] [[package]] @@ -478,9 +475,9 @@ dependencies = [ [[package]] name = "blocking" -version = "1.6.1" +version = "1.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703f41c54fc768e63e091340b424302bb1c29ef4aa0c7f10fe849dfb114d29ea" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" dependencies = [ "async-channel", "async-task", @@ -499,6 +496,12 @@ dependencies = [ "cipher", ] +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + [[package]] name = "byteorder" version = "1.5.0" @@ -513,9 +516,9 @@ checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "camino" -version = "1.1.9" +version = "1.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" +checksum = "dd0b03af37dad7a14518b7691d81acb0f8222604ad3d1b02f6b4bed5188c0cd5" dependencies = [ "serde", ] @@ -563,9 +566,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" @@ -614,14 +617,42 @@ dependencies = [ "pbkdf2", "rand 0.9.1", "rusqlite", - "security-framework", + "security-framework 3.5.0", "serde", "serde_json", "sha1", "tokio", "tracing", "tracing-subscriber", - "windows 0.61.1", + "verifysign", + "windows 0.62.2", +] + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", ] [[package]] @@ -671,24 +702,24 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" +checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" [[package]] name = "clipboard-win" -version = "5.4.0" +version = "5.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15efe7a882b08f34e38556b14f2fb3daa98769d06c7f0c1b076dfd0d983bc892" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" dependencies = [ "error-code", ] [[package]] name = "codespan-reporting" -version = "0.12.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" dependencies = [ "serde", "termcolor", @@ -697,9 +728,9 @@ dependencies = [ [[package]] name = "colorchoice" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] name = "concurrent-queue" @@ -725,6 +756,16 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -756,6 +797,12 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-bigint" version = "0.5.5" @@ -843,26 +890,28 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.158" +version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a71ea7f29c73f7ffa64c50b83c9fe4d3a6d4be89a86b009eb80d5a6d3429d741" +checksum = "d8465678d499296e2cbf9d3acf14307458fd69b471a31b65b3c519efe8b5e187" dependencies = [ "cc", + "cxx-build", "cxxbridge-cmd", "cxxbridge-flags", "cxxbridge-macro", - "foldhash", + "foldhash 0.2.0", "link-cplusplus", ] [[package]] name = "cxx-build" -version = "1.0.158" +version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36a8232661d66dcf713394726157d3cfe0a89bfc85f52d6e9f9bbc2306797fe7" +checksum = "d74b6bcf49ebbd91f1b1875b706ea46545032a14003b5557b7dfa4bbeba6766e" dependencies = [ "cc", "codespan-reporting", + "indexmap", "proc-macro2", "quote", "scratch", @@ -871,12 +920,13 @@ dependencies = [ [[package]] name = "cxxbridge-cmd" -version = "1.0.158" +version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f44296c8693e9ea226a48f6a122727f77aa9e9e338380cb021accaeeb7ee279" +checksum = "94ca2ad69673c4b35585edfa379617ac364bccd0ba0adf319811ba3a74ffa48a" dependencies = [ "clap", "codespan-reporting", + "indexmap", "proc-macro2", "quote", "syn", @@ -884,19 +934,19 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.158" +version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c42f69c181c176981ae44ba9876e2ea41ce8e574c296b38d06925ce9214fb8e4" +checksum = "d29b52102aa395386d77d322b3a0522f2035e716171c2c60aa87cc5e9466e523" [[package]] name = "cxxbridge-macro" -version = "1.0.158" +version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8faff5d4467e0709448187df29ccbf3b0982cc426ee444a193f87b11afb565a8" +checksum = "2a8ebf0b6138325af3ec73324cb3a48b64d57721f17291b151206782e61f66cd" dependencies = [ + "indexmap", "proc-macro2", "quote", - "rustversion", "syn", ] @@ -938,7 +988,7 @@ dependencies = [ "bytes", "cbc", "chacha20poly1305", - "core-foundation", + "core-foundation 0.10.1", "desktop_objc", "dirs", "ed25519", @@ -957,7 +1007,7 @@ dependencies = [ "russh-cryptovec", "scopeguard", "secmem-proc", - "security-framework", + "security-framework 3.5.0", "security-framework-sys", "serde", "serde_json", @@ -972,8 +1022,8 @@ dependencies = [ "tracing", "typenum", "widestring", - "windows 0.61.1", - "windows-future", + "windows 0.62.2", + "windows-future 0.3.2", "zbus", "zbus_polkit", "zeroizing-alloc", @@ -989,6 +1039,7 @@ dependencies = [ "chromium_importer", "desktop_core", "hex", + "log", "napi", "napi-build", "napi-derive", @@ -999,7 +1050,7 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", - "windows-registry", + "windows-registry 0.6.1", "windows_plugin_authenticator", ] @@ -1009,7 +1060,7 @@ version = "0.0.0" dependencies = [ "anyhow", "cc", - "core-foundation", + "core-foundation 0.10.1", "glob", "thiserror 2.0.12", "tokio", @@ -1143,9 +1194,9 @@ dependencies = [ [[package]] name = "ed25519-dalek" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek", "ed25519", @@ -1197,6 +1248,15 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "endi" version = "1.1.0" @@ -1205,9 +1265,9 @@ checksum = "a3d8a32ae18130a3c84dd492d4215c3d913c3b07c6b63c2eb3eb7ff1101ab7bf" [[package]] name = "enumflags2" -version = "0.7.11" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba2f4b465f5318854c6f8dd686ede6c0a9dc67d4b1ac241cf0eb51521a309147" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" dependencies = [ "enumflags2_derive", "serde", @@ -1215,9 +1275,9 @@ dependencies = [ [[package]] name = "enumflags2_derive" -version = "0.7.11" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc4caf64a58d7a6d65ab00639b046ff54399a39f5f2554728895ace4b297cd79" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" dependencies = [ "proc-macro2", "quote", @@ -1232,12 +1292,12 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" -version = "0.3.11" +version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -1248,9 +1308,9 @@ checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" [[package]] name = "event-listener" -version = "5.4.0" +version = "5.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3492acde4c3fc54c845eaab3eed8bd00c7a7d881f78bfc801e43a93dec1331ae" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" dependencies = [ "concurrent-queue", "parking", @@ -1320,10 +1380,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] -name = "form_urlencoded" -version = "1.2.1" +name = "foldhash" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" dependencies = [ "percent-encoding", ] @@ -1393,9 +1474,9 @@ checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" -version = "2.6.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" dependencies = [ "fastrand", "futures-core", @@ -1447,9 +1528,9 @@ dependencies = [ [[package]] name = "generic-array" -version = "0.14.7" +version = "0.14.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" dependencies = [ "typenum", "version_check", @@ -1458,12 +1539,12 @@ dependencies = [ [[package]] name = "gethostname" -version = "0.4.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0176e0459c2e4a1fe232f984bca6890e681076abb9934f6cea7c326f3fc47818" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "libc", - "windows-targets 0.48.5", + "rustix 1.1.2", + "windows-link 0.2.1", ] [[package]] @@ -1474,19 +1555,19 @@ checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi", ] [[package]] name = "getrandom" -version = "0.3.3" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", "r-efi", - "wasi 0.14.2+wasi-0.2.4", + "wasip2", ] [[package]] @@ -1501,9 +1582,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.31.1" +version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" [[package]] name = "glob" @@ -1533,6 +1614,36 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c0b69cfcb4e1b9f1bf2f53f95f766e4661169728ec61cd3fe5a0166f2d1386" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -1541,20 +1652,26 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" [[package]] name = "hashbrown" -version = "0.15.3" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "foldhash", + "foldhash 0.1.5", ] +[[package]] +name = "hashbrown" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" + [[package]] name = "hashlink" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" dependencies = [ - "hashbrown 0.15.3", + "hashbrown 0.15.5", ] [[package]] @@ -1565,9 +1682,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.4.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" [[package]] name = "hex" @@ -1606,10 +1723,130 @@ dependencies = [ ] [[package]] -name = "icu_collections" -version = "2.0.0" +name = "http" +version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" +checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb3aa54a13a0dfe7fbe3a59e0c76093041720fdc77b110cc0fc260fafb4dc51e" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.1", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry 0.5.3", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" dependencies = [ "displaydoc", "potential_utf", @@ -1620,9 +1857,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" dependencies = [ "displaydoc", "litemap", @@ -1633,11 +1870,10 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" dependencies = [ - "displaydoc", "icu_collections", "icu_normalizer_data", "icu_properties", @@ -1648,42 +1884,38 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" [[package]] name = "icu_properties" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2549ca8c7241c82f59c80ba2a6f415d931c5b58d24fb8412caa1a1f02c49139a" +checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" dependencies = [ - "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", "icu_provider", - "potential_utf", "zerotrie", "zerovec", ] [[package]] name = "icu_properties_data" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8197e866e47b68f8f7d95249e172903bec06004b18b2937f1095d40a0c57de04" +checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" [[package]] name = "icu_provider" -version = "2.0.0" +version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" dependencies = [ "displaydoc", "icu_locale_core", - "stable_deref_trait", - "tinystr", "writeable", "yoke", "zerofrom", @@ -1693,9 +1925,9 @@ dependencies = [ [[package]] name = "idna" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" dependencies = [ "idna_adapter", "smallvec", @@ -1714,12 +1946,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.9.0" +version = "2.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e" +checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f" dependencies = [ "equivalent", - "hashbrown 0.15.3", + "hashbrown 0.16.0", ] [[package]] @@ -1748,10 +1980,26 @@ dependencies = [ ] [[package]] -name = "is_terminal_polyfill" -version = "1.70.1" +name = "ipnet" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" +checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" + +[[package]] +name = "iri-string" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" @@ -1759,6 +2007,16 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "js-sys" +version = "0.3.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "keytar" version = "0.1.6" @@ -1797,12 +2055,12 @@ checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" [[package]] name = "libloading" -version = "0.8.7" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a793df0d7afeac54f95b471d3af7f0d4fb975699f972341a4b76988d49cdf0c" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-targets 0.53.3", + "windows-link 0.2.1", ] [[package]] @@ -1813,9 +2071,9 @@ checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" -version = "0.1.3" +version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" dependencies = [ "bitflags", "libc", @@ -1834,9 +2092,9 @@ dependencies = [ [[package]] name = "link-cplusplus" -version = "1.0.10" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a6f6da007f968f9def0d65a05b187e2960183de70c160204ecfccf0ee330212" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" dependencies = [ "cc", ] @@ -1859,23 +2117,22 @@ checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" -version = "0.9.4" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" [[package]] name = "litemap" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" [[package]] name = "lock_api" -version = "0.4.12" +version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" dependencies = [ - "autocfg", "scopeguard", ] @@ -1923,9 +2180,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" [[package]] name = "memoffset" @@ -1971,22 +2228,22 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", ] [[package]] name = "mio" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" +checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" dependencies = [ "libc", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.52.0", + "wasi", + "windows-sys 0.61.2", ] [[package]] @@ -2073,6 +2330,23 @@ dependencies = [ "libloading", ] +[[package]] +name = "native-tls" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87de3442987e9dbec73158d5c715e7ad9072fda936bb03d19d7fa10e00520f0e" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework 2.11.1", + "security-framework-sys", + "tempfile", +] + [[package]] name = "nix" version = "0.29.0" @@ -2119,11 +2393,11 @@ dependencies = [ [[package]] name = "nu-ansi-term" -version = "0.50.1" +version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a28e057d01f97e61255210fcff094d74ed0466038633e95017f5beb68e4399" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2220,18 +2494,18 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.1" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88c6597e14493ab2e44ce58f2fdecf095a51f12ca57bec060a11c57332520551" +checksum = "b7c2599ce0ec54857b29ce62166b0ed9b4f6f1a70ccc9a71165b6154caca8c05" dependencies = [ "objc2-encode", ] [[package]] name = "objc2-app-kit" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6f29f568bec459b0ddff777cec4fe3fd8666d82d5a40ebd0ff7e66134f89bcc" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags", "objc2", @@ -2241,9 +2515,9 @@ dependencies = [ [[package]] name = "objc2-core-foundation" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c10c2894a6fed806ade6027bcd50662746363a9589d3ec9d9bef30a4e4bc166" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ "bitflags", "dispatch2", @@ -2252,9 +2526,9 @@ dependencies = [ [[package]] name = "objc2-core-graphics" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989c6c68c13021b5c2d6b71456ebb0f9dc78d752e86a98da7c716f4f9470f5a4" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ "bitflags", "dispatch2", @@ -2271,9 +2545,9 @@ checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" [[package]] name = "objc2-foundation" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "900831247d2fe1a09a683278e5384cfb8c80c79fe6b166f9d14bfdde0ea1b03c" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags", "objc2", @@ -2282,9 +2556,9 @@ dependencies = [ [[package]] name = "objc2-io-kit" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71c1c64d6120e51cd86033f67176b1cb66780c2efe34dec55176f77befd93c0a" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" dependencies = [ "libc", "objc2-core-foundation", @@ -2292,9 +2566,9 @@ dependencies = [ [[package]] name = "objc2-io-surface" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7282e9ac92529fa3457ce90ebb15f4ecbc383e8338060960760fa2cf75420c3c" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ "bitflags", "objc2", @@ -2303,9 +2577,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.7" +version = "0.37.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" dependencies = [ "memchr", ] @@ -2316,6 +2590,12 @@ version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oo7" version = "0.4.3" @@ -2329,7 +2609,7 @@ dependencies = [ "digest", "endi", "futures-util", - "getrandom 0.3.3", + "getrandom 0.3.4", "hkdf", "hmac", "md-5", @@ -2353,6 +2633,50 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "openssl" +version = "0.10.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24ad14dd45412269e1a30f52ad8f0664f0f4f4a89ee8fe28c3b3527021ebb654" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" + +[[package]] +name = "openssl-sys" +version = "0.9.110" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a9f0075ba3c21b09f8e8b2026584b1d18d49388648f2fbbf3c97ea8deced8e2" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -2371,12 +2695,12 @@ dependencies = [ [[package]] name = "os_pipe" -version = "1.2.1" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ffd2b0a5634335b135d5728d84c5e0fd726954b87111f7506a61c502280d982" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -2436,9 +2760,9 @@ checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" [[package]] name = "parking_lot" -version = "0.12.3" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", "parking_lot_core", @@ -2446,15 +2770,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.10" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", - "windows-targets 0.52.6", + "windows-link 0.2.1", ] [[package]] @@ -2484,9 +2808,9 @@ dependencies = [ [[package]] name = "percent-encoding" -version = "2.3.1" +version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "petgraph" @@ -2593,17 +2917,16 @@ checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] name = "polling" -version = "3.7.4" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 0.38.44", - "tracing", - "windows-sys 0.59.0", + "rustix 1.1.2", + "windows-sys 0.61.2", ] [[package]] @@ -2631,9 +2954,9 @@ dependencies = [ [[package]] name = "potential_utf" -version = "0.1.2" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" dependencies = [ "zerovec", ] @@ -2684,18 +3007,18 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "3.3.0" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edce586971a4dfaa28950c6f18ed55e0406c1ab88bbce2c6f6293a7aaba73d35" +checksum = "219cb19e96be00ab2e37d6e299658a0cfa83e52429179969b0f0121b4ac46983" dependencies = [ "toml_edit", ] [[package]] name = "proc-macro2" -version = "1.0.95" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" dependencies = [ "unicode-ident", ] @@ -2721,18 +3044,18 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.40" +version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" -version = "5.2.0" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rand" @@ -2790,7 +3113,7 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.3", + "getrandom 0.3.4", ] [[package]] @@ -2801,18 +3124,18 @@ checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" [[package]] name = "redox_syscall" -version = "0.5.12" +version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928fca9cf2aa042393a8325b9ead81d2f0df4cb12e1e24cef072922ccd99c5af" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ "bitflags", ] [[package]] name = "redox_users" -version = "0.5.0" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" +checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.16", "libredox", @@ -2821,9 +3144,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.11.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" dependencies = [ "aho-corasick", "memchr", @@ -2833,9 +3156,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.9" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" dependencies = [ "aho-corasick", "memchr", @@ -2844,9 +3167,51 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.5" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "reqwest" +version = "0.12.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] [[package]] name = "rfc6979" @@ -2858,6 +3223,20 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.17.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e75ec5e92c4d8aede845126adc388046234541629e76029599ed35a003c7ed24" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsa" version = "0.9.6" @@ -2905,9 +3284,9 @@ dependencies = [ [[package]] name = "rustc-demangle" -version = "0.1.24" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" [[package]] name = "rustc_version" @@ -2933,15 +3312,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.7" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys 0.9.4", - "windows-sys 0.59.0", + "linux-raw-sys 0.11.0", + "windows-sys 0.61.2", ] [[package]] @@ -2951,14 +3330,47 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.0.7", + "rustix 1.1.2", +] + +[[package]] +name = "rustls" +version = "0.23.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a9586e9ee2b4f8fab52a0048ca7334d7024eef48e2cb9407e3497bb7cab7fa7" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] name = "rustversion" -version = "1.0.20" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "ryu" @@ -2984,6 +3396,15 @@ dependencies = [ "sdd", ] +[[package]] +name = "schannel" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891d81b926048e76efe18581bf793546b4c0eaf8448d72be8de2bbee5fd166e1" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -2992,9 +3413,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "scratch" -version = "1.0.8" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f6280af86e5f559536da57a45ebc84948833b3bee313a7dd25232e09c878a52" +checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" [[package]] name = "scroll" @@ -3056,10 +3477,23 @@ dependencies = [ "anyhow", "cfg-if", "libc", - "rustix 1.0.7", + "rustix 1.1.2", "rustix-linux-procfs", "thiserror 2.0.12", - "windows 0.61.1", + "windows 0.61.3", +] + +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", ] [[package]] @@ -3069,7 +3503,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc198e42d9b7510827939c9a15f5062a0c913f3371d765977e586d2fe6c16f4a" dependencies = [ "bitflags", - "core-foundation", + "core-foundation 0.10.1", "core-foundation-sys", "libc", "security-framework-sys", @@ -3146,6 +3580,18 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "serial_test" version = "3.2.0" @@ -3210,9 +3656,9 @@ checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "signal-hook-registry" -version = "1.4.5" +version = "1.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" +checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" dependencies = [ "libc", ] @@ -3235,18 +3681,15 @@ checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" [[package]] name = "slab" -version = "0.4.9" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" [[package]] name = "smallvec" -version = "1.15.0" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "smawk" @@ -3256,14 +3699,24 @@ checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c" [[package]] name = "socket2" -version = "0.5.9" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f5fd57c80058a56cf5c777ab8a126398ece8e442983605d280a44ce79d0edef" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ "libc", "windows-sys 0.52.0", ] +[[package]] +name = "socket2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + [[package]] name = "spin" version = "0.9.8" @@ -3330,9 +3783,9 @@ dependencies = [ [[package]] name = "stable_deref_trait" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "static_assertions" @@ -3354,15 +3807,24 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.101" +version = "2.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" +checksum = "da58917d35242480a05c2897064da0a80589a2a0476c9a3f2fdc83b53502e917" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.13.2" @@ -3385,20 +3847,41 @@ dependencies = [ "ntapi", "objc2-core-foundation", "objc2-io-kit", - "windows 0.61.1", + "windows 0.61.3", +] + +[[package]] +name = "system-configuration" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", ] [[package]] name = "tempfile" -version = "3.20.0" +version = "3.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" +checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" dependencies = [ "fastrand", - "getrandom 0.3.3", + "getrandom 0.3.4", "once_cell", - "rustix 1.0.7", - "windows-sys 0.59.0", + "rustix 1.1.2", + "windows-sys 0.61.2", ] [[package]] @@ -3476,9 +3959,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" dependencies = [ "displaydoc", "zerovec", @@ -3497,7 +3980,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.5.10", "tokio-macros", "tracing", "windows-sys 0.52.0", @@ -3514,6 +3997,26 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.15" @@ -3556,18 +4059,12 @@ dependencies = [ "indexmap", "serde", "serde_spanned", - "toml_datetime 0.7.0", + "toml_datetime", "toml_parser", "toml_writer", "winnow", ] -[[package]] -name = "toml_datetime" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3da5db5a963e24bc68be8b17b6fa82814bb22ee8660f192bb182771d498f09a3" - [[package]] name = "toml_datetime" version = "0.7.0" @@ -3579,20 +4076,21 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.26" +version = "0.23.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "310068873db2c5b3e7659d2cc35d21855dbafa50d1ce336397c666e3cb08137e" +checksum = "7211ff1b8f0d3adae1663b7da9ffe396eabe1ca25f0b0bee42b0da29a9ddce93" dependencies = [ "indexmap", - "toml_datetime 0.6.9", + "toml_datetime", + "toml_parser", "winnow", ] [[package]] name = "toml_parser" -version = "1.0.2" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b551886f449aa90d4fe2bdaa9f4a2577ad2dde302c61ecf262d80b116db95c10" +checksum = "c0cbe268d35bdb4bb5a56a2de88d0ad0eb70af5384a99d648cd4b3d04039800e" dependencies = [ "winnow", ] @@ -3603,6 +4101,51 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df8b2b54733674ad286d16267dcfc7a71ed5c776e4ac7aa3c3e2561f7c637bf2" +[[package]] +name = "tower" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.41" @@ -3616,9 +4159,9 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.28" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" +checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" dependencies = [ "proc-macro2", "quote", @@ -3627,9 +4170,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.33" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" dependencies = [ "once_cell", "valuable", @@ -3678,17 +4221,22 @@ dependencies = [ [[package]] name = "tree_magic_mini" -version = "3.1.6" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aac5e8971f245c3389a5a76e648bfc80803ae066a1243a75db0064d7c1129d63" +checksum = "f943391d896cdfe8eec03a04d7110332d445be7df856db382dd96a730667562c" dependencies = [ - "fnv", "memchr", "nom", "once_cell", "petgraph", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.18.0" @@ -3714,9 +4262,9 @@ checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" [[package]] name = "unicode-ident" -version = "1.0.18" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" [[package]] name = "unicode-segmentation" @@ -3726,9 +4274,9 @@ checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "unicode-width" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" [[package]] name = "uniffi" @@ -3871,10 +4419,16 @@ dependencies = [ ] [[package]] -name = "url" -version = "2.5.4" +name = "untrusted" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" dependencies = [ "form_urlencoded", "idna", @@ -3912,7 +4466,7 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ebfe12e38930c3b851aea35e93fab1a6c29279cad7e8e273f29a21678fee8c0" dependencies = [ - "core-foundation", + "core-foundation 0.10.1", "sha1", "sha2", "windows-sys 0.61.2", @@ -3945,50 +4499,117 @@ dependencies = [ ] [[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +name = "want" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] [[package]] name = "wasi" -version = "0.14.2+wasi-0.2.4" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" dependencies = [ - "wit-bindgen-rt", + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "551f88106c6d5e7ccc7cd9a16f312dd3b5d36ea8b4954304657d5dfba115d4a0" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" +dependencies = [ + "unicode-ident", ] [[package]] name = "wayland-backend" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe770181423e5fc79d3e2a7f4410b7799d5aab1de4372853de3c6aa13ca24121" +checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35" dependencies = [ "cc", "downcast-rs", - "rustix 0.38.44", + "rustix 1.1.2", "smallvec", "wayland-sys", ] [[package]] name = "wayland-client" -version = "0.31.10" +version = "0.31.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978fa7c67b0847dbd6a9f350ca2569174974cd4082737054dbb7fbb79d7d9a61" +checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d" dependencies = [ "bitflags", - "rustix 0.38.44", + "rustix 1.1.2", "wayland-backend", "wayland-scanner", ] [[package]] name = "wayland-protocols" -version = "0.32.8" +version = "0.32.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "779075454e1e9a521794fed15886323ea0feda3f8b0fc1390f5398141310422a" +checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901" dependencies = [ "bitflags", "wayland-backend", @@ -3998,9 +4619,9 @@ dependencies = [ [[package]] name = "wayland-protocols-wlr" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cb6cdc73399c0e06504c437fe3cf886f25568dd5454473d565085b36d6a8bbf" +checksum = "efd94963ed43cf9938a090ca4f7da58eb55325ec8200c3848963e98dc25b78ec" dependencies = [ "bitflags", "wayland-backend", @@ -4011,9 +4632,9 @@ dependencies = [ [[package]] name = "wayland-scanner" -version = "0.31.6" +version = "0.31.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "896fdafd5d28145fce7958917d69f2fd44469b1d4e861cb5961bcbeebc6d1484" +checksum = "54cb1e9dc49da91950bdfd8b848c49330536d9d1fb03d4bfec8cae50caa50ae3" dependencies = [ "proc-macro2", "quick-xml", @@ -4022,13 +4643,23 @@ dependencies = [ [[package]] name = "wayland-sys" -version = "0.31.6" +version = "0.31.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbcebb399c77d5aa9fa5db874806ee7b4eba4e73650948e8f93963f128896615" +checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142" dependencies = [ "pkg-config", ] +[[package]] +name = "web-sys" +version = "0.3.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "weedle2" version = "5.0.0" @@ -4062,11 +4693,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" -version = "0.1.9" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4087,15 +4718,27 @@ dependencies = [ [[package]] name = "windows" -version = "0.61.1" +version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5ee8f3d025738cb02bad7868bbb5f8a6327501e870bf51f1b455b0a2454a419" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", - "windows-core 0.61.0", - "windows-future", + "windows-collections 0.2.0", + "windows-core 0.61.2", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -4104,7 +4747,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" dependencies = [ - "windows-core 0.61.0", + "windows-core 0.61.2", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", ] [[package]] @@ -4121,25 +4773,50 @@ dependencies = [ [[package]] name = "windows-core" -version = "0.61.0" +version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" dependencies = [ - "windows-implement 0.60.0", - "windows-interface 0.59.1", + "windows-implement 0.60.2", + "windows-interface 0.59.3", "windows-link 0.1.3", "windows-result 0.3.4", "windows-strings 0.4.2", ] [[package]] -name = "windows-future" -version = "0.2.0" +name = "windows-core" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a1d6bbefcb7b60acd19828e1bc965da6fcf18a7e39490c5f8be71e54a19ba32" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-core 0.61.0", + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", "windows-link 0.1.3", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -4155,9 +4832,9 @@ dependencies = [ [[package]] name = "windows-implement" -version = "0.60.0" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" dependencies = [ "proc-macro2", "quote", @@ -4177,9 +4854,9 @@ dependencies = [ [[package]] name = "windows-interface" -version = "0.59.1" +version = "0.59.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ "proc-macro2", "quote", @@ -4204,10 +4881,31 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" dependencies = [ - "windows-core 0.61.0", + "windows-core 0.61.2", "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-registry" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8a9ed28765efc97bbc954883f4e6796c33a06546ebafacbabee9696967499e" +dependencies = [ + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", +] + [[package]] name = "windows-registry" version = "0.6.1" @@ -4297,7 +4995,7 @@ version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets 0.53.3", + "windows-targets 0.53.5", ] [[package]] @@ -4324,21 +5022,6 @@ dependencies = [ "windows_x86_64_msvc 0.42.2", ] -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - [[package]] name = "windows-targets" version = "0.52.6" @@ -4357,19 +5040,37 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.53.3" +version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" dependencies = [ "windows-link 0.1.3", - "windows_aarch64_gnullvm 0.53.0", - "windows_aarch64_msvc 0.53.0", - "windows_i686_gnu 0.53.0", - "windows_i686_gnullvm 0.53.0", - "windows_i686_msvc 0.53.0", - "windows_x86_64_gnu 0.53.0", - "windows_x86_64_gnullvm 0.53.0", - "windows_x86_64_msvc 0.53.0", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", ] [[package]] @@ -4378,12 +5079,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -4392,9 +5087,9 @@ checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_gnullvm" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" [[package]] name = "windows_aarch64_msvc" @@ -4402,12 +5097,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -4416,9 +5105,9 @@ checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_aarch64_msvc" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" [[package]] name = "windows_i686_gnu" @@ -4426,12 +5115,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -4440,9 +5123,9 @@ checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnu" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" [[package]] name = "windows_i686_gnullvm" @@ -4452,9 +5135,9 @@ checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_gnullvm" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" [[package]] name = "windows_i686_msvc" @@ -4462,12 +5145,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -4476,17 +5153,28 @@ checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_i686_msvc" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" [[package]] name = "windows_plugin_authenticator" version = "0.0.0" dependencies = [ + "base64", + "ciborium", + "desktop_core", + "futures", "hex", - "windows 0.61.1", - "windows-core 0.61.0", + "reqwest", + "serde", + "serde_json", + "sha2", + "tokio", + "tracing", + "tracing-subscriber", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -4495,12 +5183,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -4509,9 +5191,9 @@ checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnu" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" [[package]] name = "windows_x86_64_gnullvm" @@ -4519,12 +5201,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -4533,9 +5209,9 @@ checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_gnullvm" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" [[package]] name = "windows_x86_64_msvc" @@ -4543,12 +5219,6 @@ version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -4557,15 +5227,15 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "windows_x86_64_msvc" -version = "0.53.0" +version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winnow" -version = "0.7.10" +version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec" +checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" dependencies = [ "memchr", ] @@ -4581,13 +5251,10 @@ dependencies = [ ] [[package]] -name = "wit-bindgen-rt" -version = "0.39.0" +name = "wit-bindgen" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" -dependencies = [ - "bitflags", -] +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "wl-clipboard-rs" @@ -4610,34 +5277,33 @@ dependencies = [ [[package]] name = "writeable" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" [[package]] name = "x11rb" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d91ffca73ee7f68ce055750bf9f6eca0780b8c85eff9bc046a3b0da41755e12" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" dependencies = [ "gethostname", - "rustix 0.38.44", + "rustix 1.1.2", "x11rb-protocol", ] [[package]] name = "x11rb-protocol" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec107c4503ea0b4a98ef47356329af139c0a4f7750e621cf2973cd3385ebcb3d" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" [[package]] name = "yoke" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" dependencies = [ - "serde", "stable_deref_trait", "yoke-derive", "zerofrom", @@ -4645,9 +5311,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" dependencies = [ "proc-macro2", "quote", @@ -4691,9 +5357,9 @@ dependencies = [ [[package]] name = "zbus_macros" -version = "5.11.0" +version = "5.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57e797a9c847ed3ccc5b6254e8bcce056494b375b511b3d6edcec0aeb4defaca" +checksum = "1cdb94821ca8a87ca9c298b5d1cbd80e2a8b67115d99f6e4551ac49e42b6a314" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -4731,18 +5397,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.25" +version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1702d9583232ddb9174e01bb7c15a2ab8fb1bc6f227aa1233858c351a3ba0cb" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.25" +version = "0.8.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28a6e20d751156648aa063f3800b706ee209a32c0b4d9f24be3d980b01be55ef" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" dependencies = [ "proc-macro2", "quote", @@ -4798,9 +5464,9 @@ checksum = "ebff5e6b81c1c7dca2d0bd333b2006da48cb37dbcae5a8da888f31fcb3c19934" [[package]] name = "zerotrie" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" dependencies = [ "displaydoc", "yoke", @@ -4809,9 +5475,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.2" +version = "0.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" dependencies = [ "yoke", "zerofrom", @@ -4820,9 +5486,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" dependencies = [ "proc-macro2", "quote", @@ -4831,9 +5497,9 @@ dependencies = [ [[package]] name = "zvariant" -version = "5.7.0" +version = "5.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "999dd3be73c52b1fccd109a4a81e4fcd20fab1d3599c8121b38d04e1419498db" +checksum = "2be61892e4f2b1772727be11630a62664a1826b62efa43a6fe7449521cb8744c" dependencies = [ "endi", "enumflags2", @@ -4846,9 +5512,9 @@ dependencies = [ [[package]] name = "zvariant_derive" -version = "5.7.0" +version = "5.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6643fd0b26a46d226bd90d3f07c1b5321fe9bb7f04673cb37ac6d6883885b68e" +checksum = "da58575a1b2b20766513b1ec59d8e2e68db2745379f961f86650655e862d2006" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -4859,14 +5525,13 @@ dependencies = [ [[package]] name = "zvariant_utils" -version = "3.2.0" +version = "3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e16edfee43e5d7b553b77872d99bc36afdda75c223ca7ad5e3fbecd82ca5fc34" +checksum = "c6949d142f89f6916deca2232cf26a8afacf2b9fdc35ce766105e104478be599" dependencies = [ "proc-macro2", "quote", "serde", - "static_assertions", "syn", "winnow", ] diff --git a/apps/desktop/desktop_native/Cargo.toml b/apps/desktop/desktop_native/Cargo.toml index 7a835b81c1b..1c0b8b7bed9 100644 --- a/apps/desktop/desktop_native/Cargo.toml +++ b/apps/desktop/desktop_native/Cargo.toml @@ -77,9 +77,9 @@ tracing-subscriber = { version = "=0.3.20", features = [ typenum = "=1.18.0" uniffi = "=0.28.3" widestring = "=1.2.0" -windows = "=0.61.1" -windows-core = "=0.61.0" -windows-future = "=0.2.0" +windows = { version = "=0.62.2", features = ["Win32_System_Threading"] } +windows-core = "=0.62.2" +windows-future = "=0.3.2" windows-registry = "=0.6.1" zbus = "=5.11.0" zbus_polkit = "=5.0.0" diff --git a/apps/desktop/desktop_native/build.js b/apps/desktop/desktop_native/build.js index a7ed89a9c17..9294b45b69b 100644 --- a/apps/desktop/desktop_native/build.js +++ b/apps/desktop/desktop_native/build.js @@ -34,14 +34,15 @@ function buildNapiModule(target, release = true) { function buildProxyBin(target, release = true) { const targetArg = target ? `--target ${target}` : ""; const releaseArg = release ? "--release" : ""; - child_process.execSync(`cargo build --bin desktop_proxy ${releaseArg} ${targetArg}`, {stdio: 'inherit', cwd: path.join(__dirname, "proxy")}); + const xwin = target && target.includes('windows') && process.platform !== "win32" ? "xwin" : ""; + child_process.execSync(`cargo ${xwin} build --bin desktop_proxy ${releaseArg} ${targetArg}`, {stdio: 'inherit', cwd: path.join(__dirname, "proxy")}); if (target) { // Copy the resulting binary to the dist folder const targetFolder = release ? "release" : "debug"; - const ext = process.platform === "win32" ? ".exe" : ""; - const nodeArch = rustTargetsMap[target].nodeArch; - fs.copyFileSync(path.join(__dirname, "target", target, targetFolder, `desktop_proxy${ext}`), path.join(__dirname, "dist", `desktop_proxy.${process.platform}-${nodeArch}${ext}`)); + const { nodeArch, platform } = rustTargetsMap[target]; + const ext = platform === "win32" ? ".exe" : ""; + fs.copyFileSync(path.join(__dirname, "target", target, targetFolder, `desktop_proxy${ext}`), path.join(__dirname, "dist", `desktop_proxy.${platform}-${nodeArch}${ext}`)); } } diff --git a/apps/desktop/desktop_native/core/Cargo.toml b/apps/desktop/desktop_native/core/Cargo.toml index f6c9d669df6..6e7ad240144 100644 --- a/apps/desktop/desktop_native/core/Cargo.toml +++ b/apps/desktop/desktop_native/core/Cargo.toml @@ -69,6 +69,8 @@ windows = { workspace = true, features = [ "Win32_Foundation", "Win32_Security_Credentials", "Win32_Security_Cryptography", + "Win32_System_Com", + "Win32_System_LibraryLoader", "Win32_System_WinRT", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging", diff --git a/apps/desktop/desktop_native/core/src/autofill/mod.rs b/apps/desktop/desktop_native/core/src/autofill/mod.rs index aacec852e90..c6a9cdc6625 100644 --- a/apps/desktop/desktop_native/core/src/autofill/mod.rs +++ b/apps/desktop/desktop_native/core/src/autofill/mod.rs @@ -4,3 +4,125 @@ #[cfg_attr(target_os = "macos", path = "macos.rs")] mod autofill; pub use autofill::*; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +#[derive(Deserialize)] +struct RunCommandRequest { + #[serde(rename = "namespace")] + namespace: String, + #[serde(rename = "command")] + command: RunCommand, + #[serde(rename = "params")] + params: Value, +} + +#[derive(Deserialize)] +enum RunCommand { + #[serde(rename = "status")] + Status, + #[serde(rename = "sync")] + Sync, +} + +#[derive(Debug, Deserialize)] +struct SyncParameters { + #[serde(rename = "credentials")] + pub(crate) credentials: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(tag = "type")] +enum SyncCredential { + #[serde(rename = "login")] + Login { + #[serde(rename = "cipherId")] + cipher_id: String, + password: String, + uri: String, + username: String, + }, + #[serde(rename = "fido2")] + Fido2 { + #[serde(rename = "cipherId")] + cipher_id: String, + + #[serde(rename = "rpId")] + rp_id: String, + + /// Base64-encoded + #[serde(rename = "credentialId")] + credential_id: String, + + #[serde(rename = "userName")] + user_name: String, + + /// Base64-encoded + #[serde(rename = "userHandle")] + user_handle: String, + }, +} + +#[derive(Serialize)] +struct StatusResponse { + support: StatusSupport, + state: StatusState, +} + +#[derive(Serialize)] +struct StatusSupport { + fido2: bool, + password: bool, + #[serde(rename = "incrementalUpdates")] + incremental_updates: bool, +} + +#[derive(Serialize)] +struct StatusState { + enabled: bool, +} + +#[derive(Serialize)] +struct SyncResponse { + added: u32, +} + +#[derive(Serialize)] +#[serde(tag = "type")] +enum CommandResponse { + #[serde(rename = "success")] + Success { value: Value }, + #[serde(rename = "error")] + Error { error: String }, +} + +impl From> for CommandResponse { + fn from(value: anyhow::Result) -> Self { + match value { + Ok(response) => Self::Success { value: response }, + Err(err) => Self::Error { + error: err.to_string(), + }, + } + } +} + +impl TryFrom for CommandResponse { + type Error = anyhow::Error; + + fn try_from(response: StatusResponse) -> Result { + Ok(Self::Success { + value: serde_json::to_value(response)?, + }) + } +} + +impl TryFrom for CommandResponse { + type Error = anyhow::Error; + + fn try_from(response: SyncResponse) -> Result { + Ok(Self::Success { + value: serde_json::to_value(response)?, + }) + } +} diff --git a/apps/desktop/desktop_native/core/src/autofill/windows.rs b/apps/desktop/desktop_native/core/src/autofill/windows.rs index 09dc6867931..4beac2c4c52 100644 --- a/apps/desktop/desktop_native/core/src/autofill/windows.rs +++ b/apps/desktop/desktop_native/core/src/autofill/windows.rs @@ -1,6 +1,625 @@ -use anyhow::Result; +use std::alloc; +use std::mem::{align_of, MaybeUninit}; +use std::ptr::NonNull; + +use anyhow::{anyhow, Result}; +use base64::engine::{general_purpose::URL_SAFE_NO_PAD, Engine}; +use windows::core::s; +use windows::Win32::Foundation::FreeLibrary; +use windows::{ + core::{GUID, HRESULT, PCSTR}, + Win32::System::{Com::CoTaskMemAlloc, LibraryLoader::*}, +}; + +use crate::autofill::{ + CommandResponse, RunCommand, RunCommandRequest, StatusResponse, StatusState, StatusSupport, + SyncCredential, SyncParameters, SyncResponse, +}; + +const PLUGIN_CLSID: &str = "0f7dc5d9-69ce-4652-8572-6877fd695062"; #[allow(clippy::unused_async)] -pub async fn run_command(_value: String) -> Result { - todo!("Windows does not support autofill"); +pub async fn run_command(value: String) -> Result { + // this.logService.info("Passkey request received:", { error, event }); + + let request: RunCommandRequest = serde_json::from_str(&value) + .map_err(|e| anyhow!("Failed to deserialize passkey request: {e}"))?; + + if request.namespace != "autofill" { + return Err(anyhow!("Unknown namespace: {}", request.namespace)); + } + let response: CommandResponse = match request.command { + RunCommand::Status => handle_status_request()?.try_into()?, + RunCommand::Sync => { + let params: SyncParameters = serde_json::from_value(request.params) + .map_err(|e| anyhow!("Could not parse sync parameters: {e}"))?; + handle_sync_request(params)?.try_into()? + } + }; + serde_json::to_string(&response).map_err(|e| anyhow!("Failed to serialize response: {e}")) + + /* + try { + const request = JSON.parse(event.requestJson); + this.logService.info("Parsed passkey request:", { type: event.requestType, request }); + + // Handle different request types based on the requestType field + switch (event.requestType) { + case "assertion": + return await this.handleAssertionRequest(request); + case "registration": + return await this.handleRegistrationRequest(request); + case "sync": + return await this.handleSyncRequest(request); + default: + this.logService.error("Unknown passkey request type:", event.requestType); + return JSON.stringify({ + type: "error", + message: `Unknown request type: ${event.requestType}`, + }); + } + } catch (parseError) { + this.logService.error("Failed to parse passkey request:", parseError); + return JSON.stringify({ + type: "error", + message: "Failed to parse request JSON", + }); + } + */ } + +fn handle_sync_request(params: SyncParameters) -> Result { + let credentials: Vec = params + .credentials + .into_iter() + .filter_map(|c| c.try_into().ok()) + .collect(); + let num_creds = credentials.len().try_into().unwrap_or(u32::MAX); + sync_credentials_to_windows(credentials, PLUGIN_CLSID) + .map_err(|e| anyhow!("Failed to sync credentials to Windows: {e}"))?; + Ok(SyncResponse { added: num_creds }) + /* + let mut log_file = std::fs::File::options() + .append(true) + .open("C:\\temp\\bitwarden_windows_core.log") + .unwrap(); + log_file.write_all(b"Made it to sync!"); + */ +} + +fn handle_status_request() -> Result { + Ok(StatusResponse { + support: StatusSupport { + fido2: true, + password: false, + incremental_updates: false, + }, + state: StatusState { enabled: true }, + }) +} + +/* +async fn handleAssertionRequest(request: autofill.PasskeyAssertionRequest): Promise { + this.logService.info("Handling assertion request for rpId:", request.rpId); + + try { + // Generate unique identifiers for tracking this request + const clientId = Date.now(); + const sequenceNumber = Math.floor(Math.random() * 1000000); + + // Send request and wait for response + const response = await this.sendAndOptionallyWait( + "autofill.passkeyAssertion", + { + clientId, + sequenceNumber, + request: request, + }, + { waitForResponse: true, timeout: 60000 }, + ); + + if (response) { + // Convert the response to the format expected by the NAPI bridge + return JSON.stringify({ + type: "assertion_response", + ...response, + }); + } else { + return JSON.stringify({ + type: "error", + message: "No response received from renderer", + }); + } + } catch (error) { + this.logService.error("Error in assertion request:", error); + return JSON.stringify({ + type: "error", + message: `Assertion request failed: ${error.message}`, + }); + } + } + + private async handleRegistrationRequest( + request: autofill.PasskeyRegistrationRequest, + ): Promise { + this.logService.info("Handling registration request for rpId:", request.rpId); + + try { + // Generate unique identifiers for tracking this request + const clientId = Date.now(); + const sequenceNumber = Math.floor(Math.random() * 1000000); + + // Send request and wait for response + const response = await this.sendAndOptionallyWait( + "autofill.passkeyRegistration", + { + clientId, + sequenceNumber, + request: request, + }, + { waitForResponse: true, timeout: 60000 }, + ); + + this.logService.info("Received response for registration request:", response); + + if (response) { + // Convert the response to the format expected by the NAPI bridge + return JSON.stringify({ + type: "registration_response", + ...response, + }); + } else { + return JSON.stringify({ + type: "error", + message: "No response received from renderer", + }); + } + } catch (error) { + this.logService.error("Error in registration request:", error); + return JSON.stringify({ + type: "error", + message: `Registration request failed: ${error.message}`, + }); + } + } + + private async handleSyncRequest( + request: passkey_authenticator.PasskeySyncRequest, + ): Promise { + this.logService.info("Handling sync request for rpId:", request.rpId); + + try { + // Generate unique identifiers for tracking this request + const clientId = Date.now(); + const sequenceNumber = Math.floor(Math.random() * 1000000); + + // Send sync request and wait for response + const response = await this.sendAndOptionallyWait( + "autofill.passkeySync", + { + clientId, + sequenceNumber, + request: { rpId: request.rpId }, + }, + { waitForResponse: true, timeout: 60000 }, + ); + + this.logService.info("Received response for sync request:", response); + + if (response && response.credentials) { + // Convert the response to the format expected by the NAPI bridge + return JSON.stringify({ + type: "sync_response", + credentials: response.credentials, + }); + } else { + return JSON.stringify({ + type: "error", + message: "No credentials received from renderer", + }); + } + } catch (error) { + this.logService.error("Error in sync request:", error); + return JSON.stringify({ + type: "error", + message: `Sync request failed: ${error.message}`, + }); + } + } + +*/ + +impl TryFrom for SyncedCredential { + type Error = anyhow::Error; + + fn try_from(value: SyncCredential) -> Result { + if let SyncCredential::Fido2 { + rp_id, + credential_id, + user_name, + user_handle, + .. + } = value + { + Ok(Self { + credential_id: URL_SAFE_NO_PAD + .decode(credential_id) + .map_err(|e| anyhow!("Could not decode credential ID: {e}"))?, + rp_id: rp_id, + user_name: user_name, + user_handle: URL_SAFE_NO_PAD + .decode(&user_handle) + .map_err(|e| anyhow!("Could not decode user handle: {e}"))?, + }) + } else { + Err(anyhow!("Only FIDO2 credentials are supported.")) + } + } +} + +/// Initiates credential sync from Electron to Windows - called when Electron wants to push credentials to Windows +fn sync_credentials_to_windows( + credentials: Vec, + plugin_clsid: &str, +) -> Result<(), String> { + tracing::debug!( + "[SYNC_TO_WIN] sync_credentials_to_windows called with {} credentials for plugin CLSID: {}", + credentials.len(), + plugin_clsid + ); + + // Parse CLSID string to GUID + let clsid_guid = parse_clsid_to_guid_str(plugin_clsid) + .map_err(|e| format!("Failed to parse CLSID: {}", e))?; + + if credentials.is_empty() { + tracing::debug!("[SYNC_TO_WIN] No credentials to sync, proceeding with empty sync"); + } + + // Convert Bitwarden credentials to Windows credential details + let mut win_credentials = Vec::new(); + + for (i, cred) in credentials.iter().enumerate() { + tracing::debug!("[SYNC_TO_WIN] Converting credential {}: RP ID: {}, User: {}, Credential ID: {:?} ({} bytes), User ID: {:?} ({} bytes)", + i + 1, cred.rp_id, cred.user_name, &cred.credential_id, cred.credential_id.len(), &cred.user_handle, cred.user_handle.len()); + + let win_cred = WebAuthnPluginCredentialDetails::create_from_bytes( + cred.credential_id.clone(), // Pass raw bytes + cred.rp_id.clone(), + cred.rp_id.clone(), // Use RP ID as friendly name for now + cred.user_handle.clone(), // Pass raw bytes + cred.user_name.clone(), + cred.user_name.clone(), // Use user name as display name for now + ); + + win_credentials.push(win_cred); + tracing::debug!( + "[SYNC_TO_WIN] Converted credential {} to Windows format", + i + 1 + ); + } + + // First try to remove all existing credentials for this plugin + tracing::debug!("Attempting to remove all existing credentials before sync..."); + match remove_all_credentials(clsid_guid) { + Ok(()) => { + tracing::debug!("Successfully removed existing credentials"); + } + Err(e) if e.contains("can't be loaded") => { + tracing::debug!("RemoveAllCredentials function not available - this is expected for some Windows versions"); + // This is fine, the function might not exist in all versions + } + Err(e) => { + tracing::debug!("Warning: Failed to remove existing credentials: {}", e); + // Continue anyway, as this might be the first sync or an older Windows version + } + } + + // Add the new credentials (only if we have any) + if credentials.is_empty() { + tracing::debug!("No credentials to add to Windows - sync completed successfully"); + Ok(()) + } else { + tracing::debug!("Adding new credentials to Windows..."); + match add_credentials(clsid_guid, win_credentials) { + Ok(()) => { + tracing::debug!("Successfully synced credentials to Windows"); + Ok(()) + } + Err(e) => { + tracing::error!("Failed to add credentials to Windows: {}", e); + Err(e) + } + } + } +} + +/// Credential data for sync operations +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct SyncedCredential { + pub credential_id: Vec, + pub rp_id: String, + pub user_name: String, + pub user_handle: Vec, +} + +/// Represents a credential. +/// Header File Name: _WEBAUTHN_PLUGIN_CREDENTIAL_DETAILS +/// Header File Usage: WebAuthNPluginAuthenticatorAddCredentials, etc. +#[repr(C)] +#[derive(Debug, Copy, Clone)] +struct WebAuthnPluginCredentialDetails { + pub credential_id_byte_count: u32, + pub credential_id_pointer: *const u8, // Changed to const in stable + pub rpid: *const u16, // Changed to const (LPCWSTR) + pub rp_friendly_name: *const u16, // Changed to const (LPCWSTR) + pub user_id_byte_count: u32, + pub user_id_pointer: *const u8, // Changed to const + pub user_name: *const u16, // Changed to const (LPCWSTR) + pub user_display_name: *const u16, // Changed to const (LPCWSTR) +} + +impl WebAuthnPluginCredentialDetails { + pub fn create_from_bytes( + credential_id: Vec, + rpid: String, + rp_friendly_name: String, + user_id: Vec, + user_name: String, + user_display_name: String, + ) -> Self { + // Allocate credential_id bytes with COM + let (credential_id_pointer, credential_id_byte_count) = + ComBuffer::from_buffer(&credential_id); + + // Allocate user_id bytes with COM + let (user_id_pointer, user_id_byte_count) = ComBuffer::from_buffer(&user_id); + + // Convert strings to null-terminated wide strings using trait methods + let (rpid_ptr, _) = rpid.to_com_utf16(); + let (rp_friendly_name_ptr, _) = rp_friendly_name.to_com_utf16(); + let (user_name_ptr, _) = user_name.to_com_utf16(); + let (user_display_name_ptr, _) = user_display_name.to_com_utf16(); + + Self { + credential_id_byte_count, + credential_id_pointer: credential_id_pointer as *const u8, + rpid: rpid_ptr as *const u16, + rp_friendly_name: rp_friendly_name_ptr as *const u16, + user_id_byte_count, + user_id_pointer: user_id_pointer as *const u8, + user_name: user_name_ptr as *const u16, + user_display_name: user_display_name_ptr as *const u16, + } + } +} + +// Stable API function signatures - now use REFCLSID and flat arrays +type WebAuthNPluginAuthenticatorAddCredentialsFnDeclaration = unsafe extern "cdecl" fn( + rclsid: *const GUID, // Changed from string to GUID reference + cCredentialDetails: u32, + pCredentialDetails: *const WebAuthnPluginCredentialDetails, // Flat array, not list +) -> HRESULT; + +/// Trait for converting strings to Windows-compatible wide strings using COM allocation +pub trait WindowsString { + /// Converts to null-terminated UTF-16 using COM allocation + fn to_com_utf16(&self) -> (*mut u16, u32); + /// Converts to Vec for temporary use (caller must keep Vec alive) + fn to_utf16(&self) -> Vec; +} + +impl WindowsString for str { + fn to_com_utf16(&self) -> (*mut u16, u32) { + let mut wide_vec: Vec = self.encode_utf16().collect(); + wide_vec.push(0); // null terminator + let wide_bytes: Vec = wide_vec.iter().flat_map(|&x| x.to_le_bytes()).collect(); + let (ptr, byte_count) = ComBuffer::from_buffer(&wide_bytes); + (ptr as *mut u16, byte_count) + } + + fn to_utf16(&self) -> Vec { + let mut wide_vec: Vec = self.encode_utf16().collect(); + wide_vec.push(0); // null terminator + wide_vec + } +} + +#[repr(transparent)] +pub struct ComBuffer(NonNull>); + +impl ComBuffer { + /// Returns an COM-allocated buffer of `size`. + fn alloc(size: usize, for_slice: bool) -> Self { + #[expect(clippy::as_conversions)] + { + assert!(size <= isize::MAX as usize, "requested bad object size"); + } + + // SAFETY: Any size is valid to pass to Windows, even `0`. + let ptr = NonNull::new(unsafe { CoTaskMemAlloc(size) }).unwrap_or_else(|| { + // XXX: This doesn't have to be correct, just close enough for an OK OOM error. + let layout = alloc::Layout::from_size_align(size, align_of::()).unwrap(); + alloc::handle_alloc_error(layout) + }); + + if for_slice { + // Ininitialize the buffer so it can later be treated as `&mut [u8]`. + // SAFETY: The pointer is valid and we are using a valid value for a byte-wise allocation. + unsafe { ptr.write_bytes(0, size) }; + } + + Self(ptr.cast()) + } + + fn into_ptr(self) -> *mut T { + self.0.cast().as_ptr() + } + + /// Creates a new COM-allocated structure. + /// + /// Note that `T` must be [Copy] to avoid any possible memory leaks. + pub fn with_object(object: T) -> *mut T { + // NB: Vendored from Rust's alloc code since we can't yet allocate `Box` with a custom allocator. + const MIN_ALIGN: usize = if cfg!(target_pointer_width = "64") { + 16 + } else if cfg!(target_pointer_width = "32") { + 8 + } else { + panic!("unsupported arch") + }; + + // SAFETY: Validate that our alignment works for a normal size-based allocation for soundness. + let layout = const { + let layout = alloc::Layout::new::(); + assert!(layout.align() <= MIN_ALIGN); + layout + }; + + let buffer = Self::alloc(layout.size(), false); + // SAFETY: `ptr` is valid for writes of `T` because we correctly allocated the right sized buffer that + // accounts for any alignment requirements. + // + // Additionally, we ensure the value is treated as moved by forgetting the source. + unsafe { buffer.0.cast::().write(object) }; + buffer.into_ptr() + } + + pub fn from_buffer>(buffer: T) -> (*mut u8, u32) { + let buffer = buffer.as_ref(); + let len = buffer.len(); + let com_buffer = Self::alloc(len, true); + + // SAFETY: `ptr` points to a valid allocation that `len` matches, and we made sure + // the bytes were initialized. Additionally, bytes have no alignment requirements. + unsafe { + NonNull::slice_from_raw_parts(com_buffer.0.cast::(), len) + .as_mut() + .copy_from_slice(buffer) + } + + // Safety: The Windows API structures these buffers are placed into use `u32` (`DWORD`) to + // represent length. + #[expect(clippy::as_conversions)] + (com_buffer.into_ptr(), len as u32) + } +} + +/// Converts a CLSID string to a GUID +pub(crate) fn parse_clsid_to_guid_str(clsid_str: &str) -> Result { + // Remove hyphens and parse as hex + let clsid_clean = clsid_str.replace("-", ""); + if clsid_clean.len() != 32 { + return Err("Invalid CLSID format".to_string()); + } + + // Convert to u128 and create GUID + let clsid_u128 = u128::from_str_radix(&clsid_clean, 16) + .map_err(|_| "Failed to parse CLSID as hex".to_string())?; + + Ok(GUID::from_u128(clsid_u128)) +} + +pub fn remove_all_credentials(clsid_guid: GUID) -> std::result::Result<(), String> { + tracing::debug!("Loading WebAuthNPluginAuthenticatorRemoveAllCredentials function..."); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorRemoveAllCredentials"), + ) + }; + + match result { + Some(api) => { + tracing::debug!("Function loaded successfully, calling API..."); + + let result = unsafe { api(&clsid_guid) }; + + if result.is_err() { + let error_code = result.0; + tracing::debug!("API call failed with HRESULT: 0x{:x}", error_code); + + return Err(format!( + "Error: Error response from WebAuthNPluginAuthenticatorRemoveAllCredentials()\nHRESULT: 0x{:x}\n{}", + error_code, result.message() + )); + } + + tracing::debug!("API call succeeded"); + Ok(()) + } + None => { + tracing::debug!("Failed to load WebAuthNPluginAuthenticatorRemoveAllCredentials function from webauthn.dll"); + Err(String::from("Error: Can't complete remove_all_credentials(), as the function WebAuthNPluginAuthenticatorRemoveAllCredentials can't be loaded.")) + } + } +} + +pub unsafe fn delay_load(library: PCSTR, function: PCSTR) -> Option { + let library = LoadLibraryExA(library, None, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + + let Ok(library) = library else { + return None; + }; + + let address = GetProcAddress(library, function); + + if address.is_some() { + return Some(std::mem::transmute_copy(&address)); + } + + _ = FreeLibrary(library); + + None +} + +fn add_credentials( + clsid_guid: GUID, + credentials: Vec, +) -> std::result::Result<(), String> { + tracing::debug!("Loading WebAuthNPluginAuthenticatorAddCredentials function..."); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorAddCredentials"), + ) + }; + + match result { + Some(api) => { + tracing::debug!("Function loaded successfully, calling API..."); + tracing::debug!("Adding {} credentials", credentials.len()); + + let credential_count = credentials.len() as u32; + let credentials_ptr = if credentials.is_empty() { + std::ptr::null() + } else { + credentials.as_ptr() + }; + + let result = unsafe { api(&clsid_guid, credential_count, credentials_ptr) }; + + if result.is_err() { + let error_code = result.0; + tracing::debug!("API call failed with HRESULT: 0x{:x}", error_code); + return Err(format!( + "Error: Error response from WebAuthNPluginAuthenticatorAddCredentials()\nHRESULT: 0x{:x}\n{}", + error_code, result.message() + )); + } + + tracing::debug!("API call succeeded"); + Ok(()) + } + None => { + tracing::debug!("Failed to load WebAuthNPluginAuthenticatorAddCredentials function from webauthn.dll"); + Err(String::from("Error: Can't complete add_credentials(), as the function WebAuthNPluginAuthenticatorAddCredentials can't be loaded.")) + } + } +} + +type WebAuthNPluginAuthenticatorRemoveAllCredentialsFnDeclaration = + unsafe extern "cdecl" fn(rclsid: *const GUID) -> HRESULT; diff --git a/apps/desktop/desktop_native/core/src/biometric/windows.rs b/apps/desktop/desktop_native/core/src/biometric/windows.rs index 8013c21bf9a..39dcdb149d7 100644 --- a/apps/desktop/desktop_native/core/src/biometric/windows.rs +++ b/apps/desktop/desktop_native/core/src/biometric/windows.rs @@ -48,7 +48,7 @@ impl super::BiometricTrait for Biometric { let operation: IAsyncOperation = unsafe { interop.RequestVerificationForWindowAsync(foreground_window, &HSTRING::from(message))? }; - let result = operation.get()?; + let result = operation.join()?; match result { UserConsentVerificationResult::Verified => Ok(true), @@ -57,7 +57,7 @@ impl super::BiometricTrait for Biometric { } async fn available() -> Result { - let ucv_available = UserConsentVerifier::CheckAvailabilityAsync()?.get()?; + let ucv_available = UserConsentVerifier::CheckAvailabilityAsync()?.join()?; match ucv_available { UserConsentVerifierAvailability::Available => Ok(true), diff --git a/apps/desktop/desktop_native/macos_provider/README.md b/apps/desktop/desktop_native/macos_provider/README.md new file mode 100644 index 00000000000..1d4c1902465 --- /dev/null +++ b/apps/desktop/desktop_native/macos_provider/README.md @@ -0,0 +1,35 @@ +# Explainer: Mac OS Native Passkey Provider + +This document describes the changes introduced in https://github.com/bitwarden/clients/pull/13963, where we introduce the MacOS Native Passkey Provider. It gives the high level explanation of the architecture and some of the quirks and additional good to know context. + +## The high level +MacOS has native APIs (similar to iOS) to allow Credential Managers to provide credentials to the MacOS autofill system (in the PR referenced above, we only provide passkeys). + +We’ve written a Swift-based native autofill-extension. It’s bundled in the app-bundle in PlugIns, similar to the safari-extension. + +This swift extension currently communicates with our Electron app through IPC based on a unix socket. The IPC implementation is done in Rust and utilized through UniFFI + NAPI bindings. + +Footnotes: + +* We're not using the IPC framework as the implementation pre-dates the IPC framework. +* Alternatives like XPC or CFMessagePort may have better support for when the app is sandboxed. + +Electron receives the messages and passes it to Angular (through the electron-renderer event system). + +Our existing fido2 services in the renderer respond to events, displaying UI as necessary, and returns the signature back through the same mechanism, allowing people to authenticate with passkeys through the native system + UI. See [Mac OS Native Passkey Workflows](https://bitwarden.atlassian.net/wiki/spaces/EN/pages/1828356098/Mac+OS+Native+Passkey+Workflows) for demo videos. + +## Typescript + UI implementations + +We utilize the same FIDO2 implementation and interface that is already present for our browser authentication. It was designed by @coroiu with multiple ‘ui environments' in mind. + +Therefore, a lot of the plumbing is implemented in /autofill/services/desktop-fido2-user-interface.service.ts, which implements the interface that our fido2 authenticator/client expects to drive UI related behaviors. + +We’ve also implemented a couple FIDO2 UI components to handle registration/sign in flows, but also improved the “modal mode” of the desktop app. + +## Modal mode + +When modal mode is activated, the desktop app turns into a smaller modal that is always on top and cannot be resized. This is done to improve the UX of performing a passkey operation (or SSH operation). Once the operation is completed, the app returns to normal mode and its previous position. + +We are not using electron modal windows, for a couple reason. It would require us to send data in yet another layer of IPC, but also because we'd need to bootstrap entire renderer/app instead of reusing the existing window. + +Some modal modes may hide the 'traffic buttons' (window controls) due to design requirements. diff --git a/apps/desktop/desktop_native/macos_provider/build.sh b/apps/desktop/desktop_native/macos_provider/build.sh index 21e2e045af4..2f7a2d03541 100755 --- a/apps/desktop/desktop_native/macos_provider/build.sh +++ b/apps/desktop/desktop_native/macos_provider/build.sh @@ -8,6 +8,9 @@ rm -r tmp mkdir -p ./tmp/target/universal-darwin/release/ +rustup target add aarch64-apple-darwin +rustup target add x86_64-apple-darwin + cargo build --package macos_provider --target aarch64-apple-darwin --release cargo build --package macos_provider --target x86_64-apple-darwin --release diff --git a/apps/desktop/desktop_native/macos_provider/src/lib.rs b/apps/desktop/desktop_native/macos_provider/src/lib.rs index 359fe213996..21da75a1d70 100644 --- a/apps/desktop/desktop_native/macos_provider/src/lib.rs +++ b/apps/desktop/desktop_native/macos_provider/src/lib.rs @@ -56,6 +56,14 @@ trait Callback: Send + Sync { fn error(&self, error: BitwardenError); } +#[derive(uniffi::Enum, Debug)] +/// Store the connection status between the macOS credential provider extension +/// and the desktop application's IPC server. +pub enum ConnectionStatus { + Connected, + Disconnected, +} + #[derive(uniffi::Object)] pub struct MacOSProviderClient { to_server_send: tokio::sync::mpsc::Sender, @@ -64,8 +72,23 @@ pub struct MacOSProviderClient { response_callbacks_counter: AtomicU32, #[allow(clippy::type_complexity)] response_callbacks_queue: Arc, Instant)>>>, + + // Flag to track connection status - atomic for thread safety without locks + connection_status: Arc, } +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +/// Store native desktop status information to use for IPC communication +/// between the application and the macOS credential provider. +pub struct NativeStatus { + key: String, + value: String, +} + +// In our callback management, 0 is a reserved sequence number indicating that a message does not have a callback. +const NO_CALLBACK_INDICATOR: u32 = 0; + #[uniffi::export] impl MacOSProviderClient { // FIXME: Remove unwraps! They panic and terminate the whole application. @@ -92,13 +115,15 @@ impl MacOSProviderClient { let client = MacOSProviderClient { to_server_send, - response_callbacks_counter: AtomicU32::new(0), + response_callbacks_counter: AtomicU32::new(1), // Start at 1 since 0 is reserved for "no callback" scenarios response_callbacks_queue: Arc::new(Mutex::new(HashMap::new())), + connection_status: Arc::new(std::sync::atomic::AtomicBool::new(false)), }; let path = desktop_core::ipc::path("af"); let queue = client.response_callbacks_queue.clone(); + let connection_status = client.connection_status.clone(); std::thread::spawn(move || { let rt = tokio::runtime::Builder::new_current_thread() @@ -116,9 +141,11 @@ impl MacOSProviderClient { match serde_json::from_str::(&message) { Ok(SerializedMessage::Command(CommandMessage::Connected)) => { info!("Connected to server"); + connection_status.store(true, std::sync::atomic::Ordering::Relaxed); } Ok(SerializedMessage::Command(CommandMessage::Disconnected)) => { info!("Disconnected from server"); + connection_status.store(false, std::sync::atomic::Ordering::Relaxed); } Ok(SerializedMessage::Message { sequence_number, @@ -156,12 +183,17 @@ impl MacOSProviderClient { client } + pub fn send_native_status(&self, key: String, value: String) { + let status = NativeStatus { key, value }; + self.send_message(status, None); + } + pub fn prepare_passkey_registration( &self, request: PasskeyRegistrationRequest, callback: Arc, ) { - self.send_message(request, Box::new(callback)); + self.send_message(request, Some(Box::new(callback))); } pub fn prepare_passkey_assertion( @@ -169,7 +201,7 @@ impl MacOSProviderClient { request: PasskeyAssertionRequest, callback: Arc, ) { - self.send_message(request, Box::new(callback)); + self.send_message(request, Some(Box::new(callback))); } pub fn prepare_passkey_assertion_without_user_interface( @@ -177,7 +209,18 @@ impl MacOSProviderClient { request: PasskeyAssertionWithoutUserInterfaceRequest, callback: Arc, ) { - self.send_message(request, Box::new(callback)); + self.send_message(request, Some(Box::new(callback))); + } + + pub fn get_connection_status(&self) -> ConnectionStatus { + let is_connected = self + .connection_status + .load(std::sync::atomic::Ordering::Relaxed); + if is_connected { + ConnectionStatus::Connected + } else { + ConnectionStatus::Disconnected + } } } @@ -199,7 +242,6 @@ enum SerializedMessage { } impl MacOSProviderClient { - // FIXME: Remove unwraps! They panic and terminate the whole application. #[allow(clippy::unwrap_used)] fn add_callback(&self, callback: Box) -> u32 { let sequence_number = self @@ -208,20 +250,23 @@ impl MacOSProviderClient { self.response_callbacks_queue .lock() - .unwrap() + .expect("response callbacks queue mutex should not be poisoned") .insert(sequence_number, (callback, Instant::now())); sequence_number } - // FIXME: Remove unwraps! They panic and terminate the whole application. #[allow(clippy::unwrap_used)] fn send_message( &self, message: impl Serialize + DeserializeOwned, - callback: Box, + callback: Option>, ) { - let sequence_number = self.add_callback(callback); + let sequence_number = if let Some(callback) = callback { + self.add_callback(callback) + } else { + NO_CALLBACK_INDICATOR + }; let message = serde_json::to_string(&SerializedMessage::Message { sequence_number, @@ -231,15 +276,17 @@ impl MacOSProviderClient { if let Err(e) = self.to_server_send.blocking_send(message) { // Make sure we remove the callback from the queue if we can't send the message - if let Some((cb, _)) = self - .response_callbacks_queue - .lock() - .unwrap() - .remove(&sequence_number) - { - cb.error(BitwardenError::Internal(format!( - "Error sending message: {e}" - ))); + if sequence_number != NO_CALLBACK_INDICATOR { + if let Some((callback, _)) = self + .response_callbacks_queue + .lock() + .expect("response callbacks queue mutex should not be poisoned") + .remove(&sequence_number) + { + callback.error(BitwardenError::Internal(format!( + "Error sending message: {e}" + ))); + } } } } diff --git a/apps/desktop/desktop_native/macos_provider/src/registration.rs b/apps/desktop/desktop_native/macos_provider/src/registration.rs index 9e697b75c16..c961566a86c 100644 --- a/apps/desktop/desktop_native/macos_provider/src/registration.rs +++ b/apps/desktop/desktop_native/macos_provider/src/registration.rs @@ -14,6 +14,7 @@ pub struct PasskeyRegistrationRequest { user_verification: UserVerification, supported_algorithms: Vec, window_xy: Position, + excluded_credentials: Vec>, } #[derive(uniffi::Record, Serialize, Deserialize)] diff --git a/apps/desktop/desktop_native/napi/Cargo.toml b/apps/desktop/desktop_native/napi/Cargo.toml index 4198baa4b5a..ad5950628f7 100644 --- a/apps/desktop/desktop_native/napi/Cargo.toml +++ b/apps/desktop/desktop_native/napi/Cargo.toml @@ -20,6 +20,7 @@ base64 = { workspace = true } chromium_importer = { path = "../chromium_importer" } desktop_core = { path = "../core" } hex = { workspace = true } +log = { workspace = true } napi = { workspace = true, features = ["async"] } napi-derive = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/apps/desktop/desktop_native/napi/index.d.ts b/apps/desktop/desktop_native/napi/index.d.ts index 0a8beb8c427..1221139e8fa 100644 --- a/apps/desktop/desktop_native/napi/index.d.ts +++ b/apps/desktop/desktop_native/napi/index.d.ts @@ -158,6 +158,7 @@ export declare namespace autofill { userVerification: UserVerification supportedAlgorithms: Array windowXy: Position + excludedCredentials: Array> } export interface PasskeyRegistrationResponse { rpId: string @@ -175,13 +176,17 @@ export declare namespace autofill { export interface PasskeyAssertionWithoutUserInterfaceRequest { rpId: string credentialId: Array - userName: string - userHandle: Array + userName?: string + userHandle?: Array recordIdentifier?: string clientDataHash: Array userVerification: UserVerification windowXy: Position } + export interface NativeStatus { + key: string + value: string + } export interface PasskeyAssertionResponse { rpId: string userHandle: Array @@ -197,7 +202,7 @@ export declare namespace autofill { * @param name The endpoint name to listen on. This name uniquely identifies the IPC connection and must be the same for both the server and client. * @param callback This function will be called whenever a message is received from a client. */ - static listen(name: string, registrationCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyRegistrationRequest) => void, assertionCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyAssertionRequest) => void, assertionWithoutUserInterfaceCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyAssertionWithoutUserInterfaceRequest) => void): Promise + static listen(name: string, registrationCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyRegistrationRequest) => void, assertionCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyAssertionRequest) => void, assertionWithoutUserInterfaceCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyAssertionWithoutUserInterfaceRequest) => void, nativeStatusCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: NativeStatus) => void): Promise /** Return the path to the IPC server. */ getPath(): string /** Stop the IPC server. */ diff --git a/apps/desktop/desktop_native/napi/src/lib.rs b/apps/desktop/desktop_native/napi/src/lib.rs index 39e57bd0bb5..ec663ee5539 100644 --- a/apps/desktop/desktop_native/napi/src/lib.rs +++ b/apps/desktop/desktop_native/napi/src/lib.rs @@ -682,6 +682,7 @@ pub mod autofill { pub user_verification: UserVerification, pub supported_algorithms: Vec, pub window_xy: Position, + pub excluded_credentials: Vec>, } #[napi(object)] @@ -712,14 +713,22 @@ pub mod autofill { pub struct PasskeyAssertionWithoutUserInterfaceRequest { pub rp_id: String, pub credential_id: Vec, - pub user_name: String, - pub user_handle: Vec, + pub user_name: Option, + pub user_handle: Option>, pub record_identifier: Option, pub client_data_hash: Vec, pub user_verification: UserVerification, pub window_xy: Position, } + #[napi(object)] + #[derive(Debug, Serialize, Deserialize)] + #[serde(rename_all = "camelCase")] + pub struct NativeStatus { + pub key: String, + pub value: String, + } + #[napi(object)] #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -772,6 +781,13 @@ pub mod autofill { (u32, u32, PasskeyAssertionWithoutUserInterfaceRequest), ErrorStrategy::CalleeHandled, >, + #[napi( + ts_arg_type = "(error: null | Error, clientId: number, sequenceNumber: number, message: NativeStatus) => void" + )] + native_status_callback: ThreadsafeFunction< + (u32, u32, NativeStatus), + ErrorStrategy::CalleeHandled, + >, ) -> napi::Result { let (send, mut recv) = tokio::sync::mpsc::channel::(32); tokio::spawn(async move { @@ -844,6 +860,21 @@ pub mod autofill { } } + match serde_json::from_str::>(&message) { + Ok(msg) => { + let value = msg + .value + .map(|value| (client_id, msg.sequence_number, value)) + .map_err(|e| napi::Error::from_reason(format!("{e:?}"))); + native_status_callback + .call(value, ThreadsafeFunctionCallMode::NonBlocking); + continue; + } + Err(error) => { + error!(%error, "Unable to deserialze native status."); + } + } + error!(message, "Received an unknown message2"); } } diff --git a/apps/desktop/desktop_native/napi/src/passkey_authenticator_internal/dummy.rs b/apps/desktop/desktop_native/napi/src/passkey_authenticator_internal/dummy.rs index bcd929c16b4..96908105f12 100644 --- a/apps/desktop/desktop_native/napi/src/passkey_authenticator_internal/dummy.rs +++ b/apps/desktop/desktop_native/napi/src/passkey_authenticator_internal/dummy.rs @@ -1,5 +1,29 @@ use anyhow::{bail, Result}; +use napi::threadsafe_function::{ErrorStrategy::CalleeHandled, ThreadsafeFunction}; + +// Use the PasskeyRequestEvent from the parent module +pub use crate::passkey_authenticator::{PasskeyRequestEvent, SyncedCredential}; pub fn register() -> Result<()> { bail!("Not implemented") } + +pub async fn on_request( + _callback: ThreadsafeFunction, +) -> napi::Result { + Err(napi::Error::from_reason( + "Passkey authenticator is not supported on this platform", + )) +} + +pub fn sync_credentials_to_windows(_credentials: Vec) -> napi::Result<()> { + Err(napi::Error::from_reason( + "Windows credential sync not supported on this platform", + )) +} + +pub fn get_credentials_from_windows() -> napi::Result> { + Err(napi::Error::from_reason( + "Windows credential retrieval not supported on this platform", + )) +} diff --git a/apps/desktop/desktop_native/objc/src/native/autofill/commands/sync.m b/apps/desktop/desktop_native/objc/src/native/autofill/commands/sync.m index fc13c04591a..037a97c7590 100644 --- a/apps/desktop/desktop_native/objc/src/native/autofill/commands/sync.m +++ b/apps/desktop/desktop_native/objc/src/native/autofill/commands/sync.m @@ -14,40 +14,64 @@ void runSync(void* context, NSDictionary *params) { // Map credentials to ASPasswordCredential objects NSMutableArray *mappedCredentials = [NSMutableArray arrayWithCapacity:credentials.count]; + for (NSDictionary *credential in credentials) { - NSString *type = credential[@"type"]; - - if ([type isEqualToString:@"password"]) { - NSString *cipherId = credential[@"cipherId"]; - NSString *uri = credential[@"uri"]; - NSString *username = credential[@"username"]; - - ASCredentialServiceIdentifier *serviceId = [[ASCredentialServiceIdentifier alloc] - initWithIdentifier:uri type:ASCredentialServiceIdentifierTypeURL]; - ASPasswordCredentialIdentity *credential = [[ASPasswordCredentialIdentity alloc] - initWithServiceIdentifier:serviceId user:username recordIdentifier:cipherId]; - - [mappedCredentials addObject:credential]; - } - - if (@available(macos 14, *)) { - if ([type isEqualToString:@"fido2"]) { + @try { + NSString *type = credential[@"type"]; + + if ([type isEqualToString:@"password"]) { NSString *cipherId = credential[@"cipherId"]; - NSString *rpId = credential[@"rpId"]; - NSString *userName = credential[@"userName"]; - NSData *credentialId = decodeBase64URL(credential[@"credentialId"]); - NSData *userHandle = decodeBase64URL(credential[@"userHandle"]); + NSString *uri = credential[@"uri"]; + NSString *username = credential[@"username"]; + + // Skip credentials with null username since MacOS crashes if we send credentials with empty usernames + if ([username isKindOfClass:[NSNull class]] || username.length == 0) { + NSLog(@"Skipping credential, username is empty: %@", credential); + continue; + } - Class passkeyCredentialIdentityClass = NSClassFromString(@"ASPasskeyCredentialIdentity"); - id credential = [[passkeyCredentialIdentityClass alloc] - initWithRelyingPartyIdentifier:rpId - userName:userName - credentialID:credentialId - userHandle:userHandle - recordIdentifier:cipherId]; + ASCredentialServiceIdentifier *serviceId = [[ASCredentialServiceIdentifier alloc] + initWithIdentifier:uri type:ASCredentialServiceIdentifierTypeURL]; + ASPasswordCredentialIdentity *passwordIdentity = [[ASPasswordCredentialIdentity alloc] + initWithServiceIdentifier:serviceId user:username recordIdentifier:cipherId]; - [mappedCredentials addObject:credential]; + [mappedCredentials addObject:passwordIdentity]; + } + else if (@available(macos 14, *)) { + // Fido2CredentialView uses `userName` (camelCase) while Login uses `username`. + // This is intentional. Fido2 fields are flattened from the FIDO2 spec's nested structure + // (user.name -> userName, rp.id -> rpId) to maintain a clear distinction between these fields. + if ([type isEqualToString:@"fido2"]) { + NSString *cipherId = credential[@"cipherId"]; + NSString *rpId = credential[@"rpId"]; + NSString *userName = credential[@"userName"]; + + // Skip credentials with null username since MacOS crashes if we send credentials with empty usernames + if ([userName isKindOfClass:[NSNull class]] || userName.length == 0) { + NSLog(@"Skipping credential, username is empty: %@", credential); + continue; + } + + NSData *credentialId = decodeBase64URL(credential[@"credentialId"]); + NSData *userHandle = decodeBase64URL(credential[@"userHandle"]); + + Class passkeyCredentialIdentityClass = NSClassFromString(@"ASPasskeyCredentialIdentity"); + id passkeyIdentity = [[passkeyCredentialIdentityClass alloc] + initWithRelyingPartyIdentifier:rpId + userName:userName + credentialID:credentialId + userHandle:userHandle + recordIdentifier:cipherId]; + + [mappedCredentials addObject:passkeyIdentity]; + } } + } @catch (NSException *exception) { + // Silently skip any credential that causes an exception + // to make sure we don't fail the entire sync + // There is likely some invalid data in the credential, and not something the user should/could be asked to correct. + NSLog(@"ERROR: Exception processing credential: %@ - %@", exception.name, exception.reason); + continue; } } diff --git a/apps/desktop/desktop_native/objc/src/native/utils.m b/apps/desktop/desktop_native/objc/src/native/utils.m index 040c723a8ac..8f9493a7afb 100644 --- a/apps/desktop/desktop_native/objc/src/native/utils.m +++ b/apps/desktop/desktop_native/objc/src/native/utils.m @@ -18,9 +18,26 @@ NSString *serializeJson(NSDictionary *dictionary, NSError *error) { } NSData *decodeBase64URL(NSString *base64URLString) { + if (base64URLString.length == 0) { + return nil; + } + + // Replace URL-safe characters with standard base64 characters NSString *base64String = [base64URLString stringByReplacingOccurrencesOfString:@"-" withString:@"+"]; base64String = [base64String stringByReplacingOccurrencesOfString:@"_" withString:@"/"]; - + + // Add padding if needed + // Base 64 strings should be a multiple of 4 in length + NSUInteger paddingLength = 4 - (base64String.length % 4); + if (paddingLength < 4) { + NSMutableString *paddedString = [NSMutableString stringWithString:base64String]; + for (NSUInteger i = 0; i < paddingLength; i++) { + [paddedString appendString:@"="]; + } + base64String = paddedString; + } + + // Decode the string NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; diff --git a/apps/desktop/desktop_native/rust-toolchain.toml b/apps/desktop/desktop_native/rust-toolchain.toml index 898a61f3f4b..c1ab6b3240a 100644 --- a/apps/desktop/desktop_native/rust-toolchain.toml +++ b/apps/desktop/desktop_native/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.85.0" +channel = "1.87.0" components = [ "rustfmt", "clippy" ] profile = "minimal" diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/Cargo.toml b/apps/desktop/desktop_native/windows_plugin_authenticator/Cargo.toml index 17c834325a4..89ade1f6ea4 100644 --- a/apps/desktop/desktop_native/windows_plugin_authenticator/Cargo.toml +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/Cargo.toml @@ -6,6 +6,8 @@ license = { workspace = true } publish = { workspace = true } [target.'cfg(windows)'.dependencies] +desktop_core = { path = "../core" } +futures = { workspace = true } windows = { workspace = true, features = [ "Win32_Foundation", "Win32_Security", @@ -14,6 +16,15 @@ windows = { workspace = true, features = [ ] } windows-core = { workspace = true } hex = { workspace = true } +reqwest = { version = "0.12", features = ["json", "blocking"] } +serde_json = { workspace = true } +serde = { workspace = true, features = ["derive"] } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } +ciborium = "0.2" +sha2 = "0.10" +tokio = { workspace = true } +base64 = { workspace = true } [lints] workspace = true diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.h b/apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.h new file mode 100644 index 00000000000..edb3ffd4f00 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.h @@ -0,0 +1,263 @@ + + +/* this ALWAYS GENERATED file contains the definitions for the interfaces */ + + + /* File created by MIDL compiler version 8.01.0628 */ +/* @@MIDL_FILE_HEADING( ) */ + + + +/* verify that the version is high enough to compile this file*/ +#ifndef __REQUIRED_RPCNDR_H_VERSION__ +#define __REQUIRED_RPCNDR_H_VERSION__ 501 +#endif + +/* verify that the version is high enough to compile this file*/ +#ifndef __REQUIRED_RPCSAL_H_VERSION__ +#define __REQUIRED_RPCSAL_H_VERSION__ 100 +#endif + +#include "rpc.h" +#include "rpcndr.h" + +#ifndef __RPCNDR_H_VERSION__ +#error this stub requires an updated version of +#endif /* __RPCNDR_H_VERSION__ */ + +#ifndef COM_NO_WINDOWS_H +#include "windows.h" +#include "ole2.h" +#endif /*COM_NO_WINDOWS_H*/ + +#ifndef __pluginauthenticator_h__ +#define __pluginauthenticator_h__ + +#if defined(_MSC_VER) && (_MSC_VER >= 1020) +#pragma once +#endif + +#ifndef DECLSPEC_XFGVIRT +#if defined(_CONTROL_FLOW_GUARD_XFG) +#define DECLSPEC_XFGVIRT(base, func) __declspec(xfg_virtual(base, func)) +#else +#define DECLSPEC_XFGVIRT(base, func) +#endif +#endif + +/* Forward Declarations */ + +#ifndef __IPluginAuthenticator_FWD_DEFINED__ +#define __IPluginAuthenticator_FWD_DEFINED__ +typedef interface IPluginAuthenticator IPluginAuthenticator; + +#endif /* __IPluginAuthenticator_FWD_DEFINED__ */ + + +/* header files for imported files */ +#include "oaidl.h" + +#ifdef __cplusplus +extern "C"{ +#endif + + +/* interface __MIDL_itf_pluginauthenticator_0000_0000 */ +/* [local] */ + +typedef +enum _WEBAUTHN_PLUGIN_REQUEST_TYPE + { + WEBAUTHN_PLUGIN_REQUEST_TYPE_CTAP2_CBOR = 0x1 + } WEBAUTHN_PLUGIN_REQUEST_TYPE; + +typedef struct _WEBAUTHN_PLUGIN_OPERATION_REQUEST + { + HWND hWnd; + GUID transactionId; + DWORD cbRequestSignature; + /* [size_is] */ byte *pbRequestSignature; + WEBAUTHN_PLUGIN_REQUEST_TYPE requestType; + DWORD cbEncodedRequest; + /* [size_is] */ byte *pbEncodedRequest; + } WEBAUTHN_PLUGIN_OPERATION_REQUEST; + +typedef struct _WEBAUTHN_PLUGIN_OPERATION_REQUEST *PWEBAUTHN_PLUGIN_OPERATION_REQUEST; + +typedef const WEBAUTHN_PLUGIN_OPERATION_REQUEST *PCWEBAUTHN_PLUGIN_OPERATION_REQUEST; + +typedef struct _WEBAUTHN_PLUGIN_OPERATION_RESPONSE + { + DWORD cbEncodedResponse; + /* [size_is] */ byte *pbEncodedResponse; + } WEBAUTHN_PLUGIN_OPERATION_RESPONSE; + +typedef struct _WEBAUTHN_PLUGIN_OPERATION_RESPONSE *PWEBAUTHN_PLUGIN_OPERATION_RESPONSE; + +typedef const WEBAUTHN_PLUGIN_OPERATION_RESPONSE *PCWEBAUTHN_PLUGIN_OPERATION_RESPONSE; + +typedef struct _WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST + { + GUID transactionId; + DWORD cbRequestSignature; + /* [size_is] */ byte *pbRequestSignature; + } WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST; + +typedef struct _WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST *PWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST; + +typedef const WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST *PCWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST; + +typedef +enum _PLUGIN_LOCK_STATUS + { + PluginLocked = 0, + PluginUnlocked = ( PluginLocked + 1 ) + } PLUGIN_LOCK_STATUS; + + + +extern RPC_IF_HANDLE __MIDL_itf_pluginauthenticator_0000_0000_v0_0_c_ifspec; +extern RPC_IF_HANDLE __MIDL_itf_pluginauthenticator_0000_0000_v0_0_s_ifspec; + +#ifndef __IPluginAuthenticator_INTERFACE_DEFINED__ +#define __IPluginAuthenticator_INTERFACE_DEFINED__ + +/* interface IPluginAuthenticator */ +/* [ref][version][uuid][object] */ + + +EXTERN_C const IID IID_IPluginAuthenticator; + +#if defined(__cplusplus) && !defined(CINTERFACE) + + MIDL_INTERFACE("d26bcf6f-b54c-43ff-9f06-d5bf148625f7") + IPluginAuthenticator : public IUnknown + { + public: + virtual HRESULT STDMETHODCALLTYPE MakeCredential( + /* [in] */ __RPC__in PCWEBAUTHN_PLUGIN_OPERATION_REQUEST request, + /* [retval][out] */ __RPC__out PWEBAUTHN_PLUGIN_OPERATION_RESPONSE response) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetAssertion( + /* [in] */ __RPC__in PCWEBAUTHN_PLUGIN_OPERATION_REQUEST request, + /* [retval][out] */ __RPC__out PWEBAUTHN_PLUGIN_OPERATION_RESPONSE response) = 0; + + virtual HRESULT STDMETHODCALLTYPE CancelOperation( + /* [in] */ __RPC__in PCWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST request) = 0; + + virtual HRESULT STDMETHODCALLTYPE GetLockStatus( + /* [retval][out] */ __RPC__out PLUGIN_LOCK_STATUS *lockStatus) = 0; + + }; + + +#else /* C style interface */ + + typedef struct IPluginAuthenticatorVtbl + { + BEGIN_INTERFACE + + DECLSPEC_XFGVIRT(IUnknown, QueryInterface) + HRESULT ( STDMETHODCALLTYPE *QueryInterface )( + __RPC__in IPluginAuthenticator * This, + /* [in] */ __RPC__in REFIID riid, + /* [annotation][iid_is][out] */ + _COM_Outptr_ void **ppvObject); + + DECLSPEC_XFGVIRT(IUnknown, AddRef) + ULONG ( STDMETHODCALLTYPE *AddRef )( + __RPC__in IPluginAuthenticator * This); + + DECLSPEC_XFGVIRT(IUnknown, Release) + ULONG ( STDMETHODCALLTYPE *Release )( + __RPC__in IPluginAuthenticator * This); + + DECLSPEC_XFGVIRT(IPluginAuthenticator, MakeCredential) + HRESULT ( STDMETHODCALLTYPE *MakeCredential )( + __RPC__in IPluginAuthenticator * This, + /* [in] */ __RPC__in PCWEBAUTHN_PLUGIN_OPERATION_REQUEST request, + /* [retval][out] */ __RPC__out PWEBAUTHN_PLUGIN_OPERATION_RESPONSE response); + + DECLSPEC_XFGVIRT(IPluginAuthenticator, GetAssertion) + HRESULT ( STDMETHODCALLTYPE *GetAssertion )( + __RPC__in IPluginAuthenticator * This, + /* [in] */ __RPC__in PCWEBAUTHN_PLUGIN_OPERATION_REQUEST request, + /* [retval][out] */ __RPC__out PWEBAUTHN_PLUGIN_OPERATION_RESPONSE response); + + DECLSPEC_XFGVIRT(IPluginAuthenticator, CancelOperation) + HRESULT ( STDMETHODCALLTYPE *CancelOperation )( + __RPC__in IPluginAuthenticator * This, + /* [in] */ __RPC__in PCWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST request); + + DECLSPEC_XFGVIRT(IPluginAuthenticator, GetLockStatus) + HRESULT ( STDMETHODCALLTYPE *GetLockStatus )( + __RPC__in IPluginAuthenticator * This, + /* [retval][out] */ __RPC__out PLUGIN_LOCK_STATUS *lockStatus); + + END_INTERFACE + } IPluginAuthenticatorVtbl; + + interface IPluginAuthenticator + { + CONST_VTBL struct IPluginAuthenticatorVtbl *lpVtbl; + }; + + + +#ifdef COBJMACROS + + +#define IPluginAuthenticator_QueryInterface(This,riid,ppvObject) \ + ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) + +#define IPluginAuthenticator_AddRef(This) \ + ( (This)->lpVtbl -> AddRef(This) ) + +#define IPluginAuthenticator_Release(This) \ + ( (This)->lpVtbl -> Release(This) ) + + +#define IPluginAuthenticator_MakeCredential(This,request,response) \ + ( (This)->lpVtbl -> MakeCredential(This,request,response) ) + +#define IPluginAuthenticator_GetAssertion(This,request,response) \ + ( (This)->lpVtbl -> GetAssertion(This,request,response) ) + +#define IPluginAuthenticator_CancelOperation(This,request) \ + ( (This)->lpVtbl -> CancelOperation(This,request) ) + +#define IPluginAuthenticator_GetLockStatus(This,lockStatus) \ + ( (This)->lpVtbl -> GetLockStatus(This,lockStatus) ) + +#endif /* COBJMACROS */ + + +#endif /* C style interface */ + + + + +#endif /* __IPluginAuthenticator_INTERFACE_DEFINED__ */ + + +/* Additional Prototypes for ALL interfaces */ + +unsigned long __RPC_USER HWND_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in HWND * ); +unsigned char * __RPC_USER HWND_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HWND * ); +unsigned char * __RPC_USER HWND_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HWND * ); +void __RPC_USER HWND_UserFree( __RPC__in unsigned long *, __RPC__in HWND * ); + +unsigned long __RPC_USER HWND_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in HWND * ); +unsigned char * __RPC_USER HWND_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in HWND * ); +unsigned char * __RPC_USER HWND_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out HWND * ); +void __RPC_USER HWND_UserFree64( __RPC__in unsigned long *, __RPC__in HWND * ); + +/* end of Additional Prototypes */ + +#ifdef __cplusplus +} +#endif + +#endif + + diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.idl b/apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.idl new file mode 100644 index 00000000000..b33ca0615a2 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/include/pluginauthenticator.idl @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +import "oaidl.idl"; +import "objidl.idl"; +import "wtypes.idl"; + +typedef enum _WEBAUTHN_PLUGIN_REQUEST_TYPE { + WEBAUTHN_PLUGIN_REQUEST_TYPE_CTAP2_CBOR = 0x01 // CBOR encoded CTAP2 message. Refer to the FIDO Specifications: Client to Authenticator Protocol (CTAP) +} WEBAUTHN_PLUGIN_REQUEST_TYPE; + +typedef struct _WEBAUTHN_PLUGIN_OPERATION_REQUEST { + // Handle of the top level Window of the caller + HWND hWnd; + + // Transaction ID + GUID transactionId; + + // Request Hash Signature Bytes Buffer Size + DWORD cbRequestSignature; + + // Request Hash Signature Bytes Buffer - Signature verified using the "pbOpSignPubKey" in PWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE + [size_is(cbRequestSignature)] byte* pbRequestSignature; + + // Request Type - Determines the encoding of the request and response buffers + WEBAUTHN_PLUGIN_REQUEST_TYPE requestType; + + // Encoded Request Buffer Size + DWORD cbEncodedRequest; + + // Encoded Request Buffer - Encoding type is determined by the requestType + [size_is(cbEncodedRequest)] byte* pbEncodedRequest; +} WEBAUTHN_PLUGIN_OPERATION_REQUEST, *PWEBAUTHN_PLUGIN_OPERATION_REQUEST; +typedef const WEBAUTHN_PLUGIN_OPERATION_REQUEST *PCWEBAUTHN_PLUGIN_OPERATION_REQUEST; + +typedef struct _WEBAUTHN_PLUGIN_OPERATION_RESPONSE { + // Encoded Response Buffer Size + DWORD cbEncodedResponse; + + // Encoded Response Buffer - Encoding type must match the request + [size_is(cbEncodedResponse)] byte* pbEncodedResponse; +} WEBAUTHN_PLUGIN_OPERATION_RESPONSE, *PWEBAUTHN_PLUGIN_OPERATION_RESPONSE; +typedef const WEBAUTHN_PLUGIN_OPERATION_RESPONSE *PCWEBAUTHN_PLUGIN_OPERATION_RESPONSE; + +typedef struct _WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST { + // Transaction ID + GUID transactionId; + + // Request Hash Signature Bytes Buffer Size + DWORD cbRequestSignature; + + // Request Hash Signature Bytes Buffer - Signature verified using the "pbOpSignPubKey" in PWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE + [size_is(cbRequestSignature)] byte* pbRequestSignature; +} WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST, *PWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST; +typedef const WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST *PCWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST; + +typedef enum _PLUGIN_LOCK_STATUS { + PluginLocked = 0, + PluginUnlocked +} PLUGIN_LOCK_STATUS; + +[ + object, + uuid(d26bcf6f-b54c-43ff-9f06-d5bf148625f7), + version(1.0), + pointer_default(ref) +] +interface IPluginAuthenticator : IUnknown +{ + HRESULT MakeCredential( + [in] PCWEBAUTHN_PLUGIN_OPERATION_REQUEST request, + [out, retval] PWEBAUTHN_PLUGIN_OPERATION_RESPONSE response); + + HRESULT GetAssertion( + [in] PCWEBAUTHN_PLUGIN_OPERATION_REQUEST request, + [out, retval] PWEBAUTHN_PLUGIN_OPERATION_RESPONSE response); + + HRESULT CancelOperation( + [in] PCWEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST request); + + HRESULT GetLockStatus( + [out, retval] PLUGIN_LOCK_STATUS* lockStatus); +} \ No newline at end of file diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthn.h b/apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthn.h new file mode 100644 index 00000000000..b5eaca30f1c --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthn.h @@ -0,0 +1,1381 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#ifndef __WEBAUTHN_H_ +#define __WEBAUTHN_H_ + +#pragma once + +#include + +#pragma region Desktop Family or OneCore Family +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM) + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef WINAPI +#define WINAPI __stdcall +#endif + +#ifndef INITGUID +#define INITGUID +#include +#undef INITGUID +#else +#include +#endif + +//+------------------------------------------------------------------------------------------ +// API Version Information. +// Caller should check for WebAuthNGetApiVersionNumber to check the presence of relevant APIs +// and features for their usage. +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_API_VERSION_1 1 +// WEBAUTHN_API_VERSION_1 : Baseline Version +// Data Structures and their sub versions: +// - WEBAUTHN_RP_ENTITY_INFORMATION : 1 +// - WEBAUTHN_USER_ENTITY_INFORMATION : 1 +// - WEBAUTHN_CLIENT_DATA : 1 +// - WEBAUTHN_COSE_CREDENTIAL_PARAMETER : 1 +// - WEBAUTHN_COSE_CREDENTIAL_PARAMETERS : Not Applicable +// - WEBAUTHN_CREDENTIAL : 1 +// - WEBAUTHN_CREDENTIALS : Not Applicable +// - WEBAUTHN_CREDENTIAL_EX : 1 +// - WEBAUTHN_CREDENTIAL_LIST : Not Applicable +// - WEBAUTHN_EXTENSION : Not Applicable +// - WEBAUTHN_EXTENSIONS : Not Applicable +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 3 +// - WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS : 4 +// - WEBAUTHN_COMMON_ATTESTATION : 1 +// - WEBAUTHN_CREDENTIAL_ATTESTATION : 3 +// - WEBAUTHN_ASSERTION : 1 +// Extensions: +// - WEBAUTHN_EXTENSIONS_IDENTIFIER_HMAC_SECRET +// APIs: +// - WebAuthNGetApiVersionNumber +// - WebAuthNIsUserVerifyingPlatformAuthenticatorAvailable +// - WebAuthNAuthenticatorMakeCredential +// - WebAuthNAuthenticatorGetAssertion +// - WebAuthNFreeCredentialAttestation +// - WebAuthNFreeAssertion +// - WebAuthNGetCancellationId +// - WebAuthNCancelCurrentOperation +// - WebAuthNGetErrorName +// - WebAuthNGetW3CExceptionDOMError +// Transports: +// - WEBAUTHN_CTAP_TRANSPORT_USB +// - WEBAUTHN_CTAP_TRANSPORT_NFC +// - WEBAUTHN_CTAP_TRANSPORT_BLE +// - WEBAUTHN_CTAP_TRANSPORT_INTERNAL + +#define WEBAUTHN_API_VERSION_2 2 +// WEBAUTHN_API_VERSION_2 : Delta From WEBAUTHN_API_VERSION_1 +// Added Extensions: +// - WEBAUTHN_EXTENSIONS_IDENTIFIER_CRED_PROTECT +// + +#define WEBAUTHN_API_VERSION_3 3 +// WEBAUTHN_API_VERSION_3 : Delta From WEBAUTHN_API_VERSION_2 +// Data Structures and their sub versions: +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 4 +// - WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS : 5 +// - WEBAUTHN_CREDENTIAL_ATTESTATION : 4 +// - WEBAUTHN_ASSERTION : 2 +// Added Extensions: +// - WEBAUTHN_EXTENSIONS_IDENTIFIER_CRED_BLOB +// - WEBAUTHN_EXTENSIONS_IDENTIFIER_MIN_PIN_LENGTH +// + +#define WEBAUTHN_API_VERSION_4 4 +// WEBAUTHN_API_VERSION_4 : Delta From WEBAUTHN_API_VERSION_3 +// Data Structures and their sub versions: +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 5 +// - WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS : 6 +// - WEBAUTHN_ASSERTION : 3 +// - WEBAUTHN_GET_CREDENTIALS_OPTIONS : 1 +// - WEBAUTHN_CREDENTIAL_DETAILS : 1 +// APIs: +// - WebAuthNGetPlatformCredentialList +// - WebAuthNFreePlatformCredentialList +// - WebAuthNDeletePlatformCredential +// + +#define WEBAUTHN_API_VERSION_5 5 +// WEBAUTHN_API_VERSION_5 : Delta From WEBAUTHN_API_VERSION_4 +// Data Structures and their sub versions: +// - WEBAUTHN_CREDENTIAL_DETAILS : 2 +// Extension Changes: +// - Enabled LARGE_BLOB Support +// + +#define WEBAUTHN_API_VERSION_6 6 +// WEBAUTHN_API_VERSION_6 : Delta From WEBAUTHN_API_VERSION_5 +// Data Structures and their sub versions: +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 6 +// - WEBAUTHN_CREDENTIAL_ATTESTATION : 5 +// - WEBAUTHN_ASSERTION : 4 +// Transports: +// - WEBAUTHN_CTAP_TRANSPORT_HYBRID + +#define WEBAUTHN_API_VERSION_7 7 +// WEBAUTHN_API_VERSION_7 : Delta From WEBAUTHN_API_VERSION_6 +// Data Structures and their sub versions: +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 7 +// - WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS : 7 +// - WEBAUTHN_CREDENTIAL_ATTESTATION : 6 +// - WEBAUTHN_ASSERTION : 5 + +#define WEBAUTHN_API_VERSION_8 8 +// WEBAUTHN_API_VERSION_8 : Delta From WEBAUTHN_API_VERSION_7 +// Data Structures and their sub versions: +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 8 +// - WEBAUTHN_CREDENTIAL_DETAILS : 3 +// - WEBAUTHN_CREDENTIAL_ATTESTATION : 7 +// - WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS : 8 +// + +#define WEBAUTHN_API_VERSION_9 9 +// WEBAUTHN_API_VERSION_9 : Delta From WEBAUTHN_API_VERSION_8 +// Data Structures and their sub versions: +// - WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS : 9 +// - WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS : 9 +// - WEBAUTHN_ASSERTION : 6 +// - WEBAUTHN_CREDENTIAL_DETAILS : 4 +// - WEBAUTHN_CREDENTIAL_ATTESTATION : 8 +// - WEBAUTHN_AUTHENTICATOR_DETAILS : 1 +// - WEBAUTHN_AUTHENTICATOR_DETAILS_LIST : Not Applicable +// APIs: +// - WebAuthNGetAuthenticatorList +// - WebAuthNFreeAuthenticatorList + +#define WEBAUTHN_API_CURRENT_VERSION WEBAUTHN_API_VERSION_9 + +//+------------------------------------------------------------------------------------------ +// Information about an RP Entity +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_RP_ENTITY_INFORMATION_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_RP_ENTITY_INFORMATION { + // Version of this structure, to allow for modifications in the future. + // This field is required and should be set to CURRENT_VERSION above. + DWORD dwVersion; + + // Identifier for the RP. This field is required. + PCWSTR pwszId; + + // Contains the friendly name of the Relying Party, such as "Acme Corporation", "Widgets Inc" or "Awesome Site". + // This field is required. + PCWSTR pwszName; + + // Optional URL pointing to RP's logo. + PCWSTR pwszIcon; +} WEBAUTHN_RP_ENTITY_INFORMATION, *PWEBAUTHN_RP_ENTITY_INFORMATION; +typedef const WEBAUTHN_RP_ENTITY_INFORMATION *PCWEBAUTHN_RP_ENTITY_INFORMATION; + +//+------------------------------------------------------------------------------------------ +// Information about an User Entity +//------------------------------------------------------------------------------------------- +#define WEBAUTHN_MAX_USER_ID_LENGTH 64 + +#define WEBAUTHN_USER_ENTITY_INFORMATION_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_USER_ENTITY_INFORMATION { + // Version of this structure, to allow for modifications in the future. + // This field is required and should be set to CURRENT_VERSION above. + DWORD dwVersion; + + // Identifier for the User. This field is required. + DWORD cbId; + _Field_size_bytes_(cbId) + PBYTE pbId; + + // Contains a detailed name for this account, such as "john.p.smith@example.com". + PCWSTR pwszName; + + // Optional URL that can be used to retrieve an image containing the user's current avatar, + // or a data URI that contains the image data. + PCWSTR pwszIcon; + + // For User: Contains the friendly name associated with the user account by the Relying Party, such as "John P. Smith". + PCWSTR pwszDisplayName; +} WEBAUTHN_USER_ENTITY_INFORMATION, *PWEBAUTHN_USER_ENTITY_INFORMATION; +typedef const WEBAUTHN_USER_ENTITY_INFORMATION *PCWEBAUTHN_USER_ENTITY_INFORMATION; + +//+------------------------------------------------------------------------------------------ +// Information about client data. +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_HASH_ALGORITHM_SHA_256 L"SHA-256" +#define WEBAUTHN_HASH_ALGORITHM_SHA_384 L"SHA-384" +#define WEBAUTHN_HASH_ALGORITHM_SHA_512 L"SHA-512" + +#define WEBAUTHN_CLIENT_DATA_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_CLIENT_DATA { + // Version of this structure, to allow for modifications in the future. + // This field is required and should be set to CURRENT_VERSION above. + DWORD dwVersion; + + // Size of the pbClientDataJSON field. + DWORD cbClientDataJSON; + // UTF-8 encoded JSON serialization of the client data. + _Field_size_bytes_(cbClientDataJSON) + PBYTE pbClientDataJSON; + + // Hash algorithm ID used to hash the pbClientDataJSON field. + LPCWSTR pwszHashAlgId; +} WEBAUTHN_CLIENT_DATA, *PWEBAUTHN_CLIENT_DATA; +typedef const WEBAUTHN_CLIENT_DATA *PCWEBAUTHN_CLIENT_DATA; + +//+------------------------------------------------------------------------------------------ +// Information about credential parameters. +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY L"public-key" + +#define WEBAUTHN_COSE_ALGORITHM_ECDSA_P256_WITH_SHA256 -7 +#define WEBAUTHN_COSE_ALGORITHM_ECDSA_P384_WITH_SHA384 -35 +#define WEBAUTHN_COSE_ALGORITHM_ECDSA_P521_WITH_SHA512 -36 + +#define WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA256 -257 +#define WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA384 -258 +#define WEBAUTHN_COSE_ALGORITHM_RSASSA_PKCS1_V1_5_WITH_SHA512 -259 + +#define WEBAUTHN_COSE_ALGORITHM_RSA_PSS_WITH_SHA256 -37 +#define WEBAUTHN_COSE_ALGORITHM_RSA_PSS_WITH_SHA384 -38 +#define WEBAUTHN_COSE_ALGORITHM_RSA_PSS_WITH_SHA512 -39 + +#define WEBAUTHN_COSE_CREDENTIAL_PARAMETER_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_COSE_CREDENTIAL_PARAMETER { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Well-known credential type specifying a credential to create. + LPCWSTR pwszCredentialType; + + // Well-known COSE algorithm specifying the algorithm to use for the credential. + LONG lAlg; +} WEBAUTHN_COSE_CREDENTIAL_PARAMETER, *PWEBAUTHN_COSE_CREDENTIAL_PARAMETER; +typedef const WEBAUTHN_COSE_CREDENTIAL_PARAMETER *PCWEBAUTHN_COSE_CREDENTIAL_PARAMETER; + +typedef struct _WEBAUTHN_COSE_CREDENTIAL_PARAMETERS { + DWORD cCredentialParameters; + _Field_size_(cCredentialParameters) + PWEBAUTHN_COSE_CREDENTIAL_PARAMETER pCredentialParameters; +} WEBAUTHN_COSE_CREDENTIAL_PARAMETERS, *PWEBAUTHN_COSE_CREDENTIAL_PARAMETERS; +typedef const WEBAUTHN_COSE_CREDENTIAL_PARAMETERS *PCWEBAUTHN_COSE_CREDENTIAL_PARAMETERS; + +//+------------------------------------------------------------------------------------------ +// Information about credential. +//------------------------------------------------------------------------------------------- +#define WEBAUTHN_CREDENTIAL_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_CREDENTIAL { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Size of pbID. + DWORD cbId; + // Unique ID for this particular credential. + _Field_size_bytes_(cbId) + PBYTE pbId; + + // Well-known credential type specifying what this particular credential is. + LPCWSTR pwszCredentialType; +} WEBAUTHN_CREDENTIAL, *PWEBAUTHN_CREDENTIAL; +typedef const WEBAUTHN_CREDENTIAL *PCWEBAUTHN_CREDENTIAL; + +typedef struct _WEBAUTHN_CREDENTIALS { + DWORD cCredentials; + _Field_size_(cCredentials) + PWEBAUTHN_CREDENTIAL pCredentials; +} WEBAUTHN_CREDENTIALS, *PWEBAUTHN_CREDENTIALS; +typedef const WEBAUTHN_CREDENTIALS *PCWEBAUTHN_CREDENTIALS; + +//+------------------------------------------------------------------------------------------ +// Information about credential with extra information, such as, dwTransports +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_CTAP_TRANSPORT_USB 0x00000001 +#define WEBAUTHN_CTAP_TRANSPORT_NFC 0x00000002 +#define WEBAUTHN_CTAP_TRANSPORT_BLE 0x00000004 +#define WEBAUTHN_CTAP_TRANSPORT_TEST 0x00000008 +#define WEBAUTHN_CTAP_TRANSPORT_INTERNAL 0x00000010 +#define WEBAUTHN_CTAP_TRANSPORT_HYBRID 0x00000020 +#define WEBAUTHN_CTAP_TRANSPORT_SMART_CARD 0x00000040 +#define WEBAUTHN_CTAP_TRANSPORT_FLAGS_MASK 0x0000007F + +#define WEBAUTHN_CTAP_TRANSPORT_USB_STRING "usb" +#define WEBAUTHN_CTAP_TRANSPORT_NFC_STRING "nfc" +#define WEBAUTHN_CTAP_TRANSPORT_BLE_STRING "ble" +#define WEBAUTHN_CTAP_TRANSPORT_SMART_CARD_STRING "smart-card" +#define WEBAUTHN_CTAP_TRANSPORT_HYBRID_STRING "hybrid" +#define WEBAUTHN_CTAP_TRANSPORT_INTERNAL_STRING "internal" + +#define WEBAUTHN_CREDENTIAL_EX_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_CREDENTIAL_EX { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Size of pbID. + DWORD cbId; + // Unique ID for this particular credential. + _Field_size_bytes_(cbId) + PBYTE pbId; + + // Well-known credential type specifying what this particular credential is. + LPCWSTR pwszCredentialType; + + // Transports. 0 implies no transport restrictions. + DWORD dwTransports; +} WEBAUTHN_CREDENTIAL_EX, *PWEBAUTHN_CREDENTIAL_EX; +typedef const WEBAUTHN_CREDENTIAL_EX *PCWEBAUTHN_CREDENTIAL_EX; + +//+------------------------------------------------------------------------------------------ +// Information about credential list with extra information +//------------------------------------------------------------------------------------------- + +typedef struct _WEBAUTHN_CREDENTIAL_LIST { + DWORD cCredentials; + _Field_size_(cCredentials) + PWEBAUTHN_CREDENTIAL_EX *ppCredentials; +} WEBAUTHN_CREDENTIAL_LIST, *PWEBAUTHN_CREDENTIAL_LIST; +typedef const WEBAUTHN_CREDENTIAL_LIST *PCWEBAUTHN_CREDENTIAL_LIST; + +//+------------------------------------------------------------------------------------------ +// Information about linked devices +//------------------------------------------------------------------------------------------- + +#define CTAPCBOR_HYBRID_STORAGE_LINKED_DATA_VERSION_1 1 +#define CTAPCBOR_HYBRID_STORAGE_LINKED_DATA_CURRENT_VERSION CTAPCBOR_HYBRID_STORAGE_LINKED_DATA_VERSION_1 + +// Deprecated +typedef struct _CTAPCBOR_HYBRID_STORAGE_LINKED_DATA +{ + // Version + DWORD dwVersion; + + // Contact Id + DWORD cbContactId; + _Field_size_bytes_(cbContactId) + PBYTE pbContactId; + + // Link Id + DWORD cbLinkId; + _Field_size_bytes_(cbLinkId) + PBYTE pbLinkId; + + // Link secret + DWORD cbLinkSecret; + _Field_size_bytes_(cbLinkSecret) + PBYTE pbLinkSecret; + + // Authenticator Public Key + DWORD cbPublicKey; + _Field_size_bytes_(cbPublicKey) + PBYTE pbPublicKey; + + // Authenticator Name + PCWSTR pwszAuthenticatorName; + + // Tunnel server domain + WORD wEncodedTunnelServerDomain; +} CTAPCBOR_HYBRID_STORAGE_LINKED_DATA, *PCTAPCBOR_HYBRID_STORAGE_LINKED_DATA; +typedef const CTAPCBOR_HYBRID_STORAGE_LINKED_DATA *PCCTAPCBOR_HYBRID_STORAGE_LINKED_DATA; + +//+------------------------------------------------------------------------------------------ +// Authenticator Information for WebAuthNGetAuthenticatorList API +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS_VERSION_1 1 +#define WEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS_CURRENT_VERSION WEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS_VERSION_1 + +typedef struct _WEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + +} WEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS, *PWEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS; +typedef const WEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS *PCWEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS; + +#define WEBAUTHN_AUTHENTICATOR_DETAILS_VERSION_1 1 +#define WEBAUTHN_AUTHENTICATOR_DETAILS_CURRENT_VERSION WEBAUTHN_AUTHENTICATOR_DETAILS_VERSION_1 + +typedef struct _WEBAUTHN_AUTHENTICATOR_DETAILS { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Authenticator ID + DWORD cbAuthenticatorId; + _Field_size_bytes_(cbAuthenticatorId) + PBYTE pbAuthenticatorId; + + // Authenticator Name + PCWSTR pwszAuthenticatorName; + + // Authenticator logo (expected to be in SVG format) + DWORD cbAuthenticatorLogo; + _Field_size_bytes_(cbAuthenticatorLogo) + PBYTE pbAuthenticatorLogo; + + // Is the authenticator currently locked? When locked, this authenticator's credentials + // might not be present or updated in WebAuthNGetPlatformCredentialList. + BOOL bLocked; + +} WEBAUTHN_AUTHENTICATOR_DETAILS, *PWEBAUTHN_AUTHENTICATOR_DETAILS; +typedef const WEBAUTHN_AUTHENTICATOR_DETAILS *PCWEBAUTHN_AUTHENTICATOR_DETAILS; + +typedef struct _WEBAUTHN_AUTHENTICATOR_DETAILS_LIST { + // Authenticator Details + DWORD cAuthenticatorDetails; + _Field_size_(cAuthenticatorDetails) + PWEBAUTHN_AUTHENTICATOR_DETAILS *ppAuthenticatorDetails; + +} WEBAUTHN_AUTHENTICATOR_DETAILS_LIST, *PWEBAUTHN_AUTHENTICATOR_DETAILS_LIST; +typedef const WEBAUTHN_AUTHENTICATOR_DETAILS_LIST *PCWEBAUTHN_AUTHENTICATOR_DETAILS_LIST; + +//+------------------------------------------------------------------------------------------ +// Credential Information for WebAuthNGetPlatformCredentialList API +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_CREDENTIAL_DETAILS_VERSION_1 1 +#define WEBAUTHN_CREDENTIAL_DETAILS_VERSION_2 2 +#define WEBAUTHN_CREDENTIAL_DETAILS_VERSION_3 3 +#define WEBAUTHN_CREDENTIAL_DETAILS_VERSION_4 4 +#define WEBAUTHN_CREDENTIAL_DETAILS_CURRENT_VERSION WEBAUTHN_CREDENTIAL_DETAILS_VERSION_4 + +typedef struct _WEBAUTHN_CREDENTIAL_DETAILS { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Size of pbCredentialID. + DWORD cbCredentialID; + _Field_size_bytes_(cbCredentialID) + PBYTE pbCredentialID; + + // RP Info + PWEBAUTHN_RP_ENTITY_INFORMATION pRpInformation; + + // User Info + PWEBAUTHN_USER_ENTITY_INFORMATION pUserInformation; + + // Removable or not. + BOOL bRemovable; + + // + // The following fields have been added in WEBAUTHN_CREDENTIAL_DETAILS_VERSION_2 + // + + // Backed Up or not. + BOOL bBackedUp; + + // + // The following fields have been added in WEBAUTHN_CREDENTIAL_DETAILS_VERSION_3 + // + PCWSTR pwszAuthenticatorName; + + // The logo is expected to be in the svg format + DWORD cbAuthenticatorLogo; + _Field_size_bytes_(cbAuthenticatorLogo) + PBYTE pbAuthenticatorLogo; + + // ThirdPartyPayment Credential or not. + BOOL bThirdPartyPayment; + + // + // The following fields have been added in WEBAUTHN_CREDENTIAL_DETAILS_VERSION_4 + // + + // Applicable Transports + DWORD dwTransports; + +} WEBAUTHN_CREDENTIAL_DETAILS, *PWEBAUTHN_CREDENTIAL_DETAILS; +typedef const WEBAUTHN_CREDENTIAL_DETAILS *PCWEBAUTHN_CREDENTIAL_DETAILS; + +typedef struct _WEBAUTHN_CREDENTIAL_DETAILS_LIST { + DWORD cCredentialDetails; + _Field_size_(cCredentialDetails) + PWEBAUTHN_CREDENTIAL_DETAILS *ppCredentialDetails; +} WEBAUTHN_CREDENTIAL_DETAILS_LIST, *PWEBAUTHN_CREDENTIAL_DETAILS_LIST; +typedef const WEBAUTHN_CREDENTIAL_DETAILS_LIST *PCWEBAUTHN_CREDENTIAL_DETAILS_LIST; + +#define WEBAUTHN_GET_CREDENTIALS_OPTIONS_VERSION_1 1 +#define WEBAUTHN_GET_CREDENTIALS_OPTIONS_CURRENT_VERSION WEBAUTHN_GET_CREDENTIALS_OPTIONS_VERSION_1 + +typedef struct _WEBAUTHN_GET_CREDENTIALS_OPTIONS { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Optional. + LPCWSTR pwszRpId; + + // Optional. BrowserInPrivate Mode. Defaulting to FALSE. + BOOL bBrowserInPrivateMode; +} WEBAUTHN_GET_CREDENTIALS_OPTIONS, *PWEBAUTHN_GET_CREDENTIALS_OPTIONS; +typedef const WEBAUTHN_GET_CREDENTIALS_OPTIONS *PCWEBAUTHN_GET_CREDENTIALS_OPTIONS; + +//+------------------------------------------------------------------------------------------ +// PRF values. +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_CTAP_ONE_HMAC_SECRET_LENGTH 32 + +// SALT values below by default are converted into RAW Hmac-Secret values as per PRF extension. +// - SHA-256(UTF8Encode("WebAuthn PRF") || 0x00 || Value) +// +// Set WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG in dwFlags in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS, +// if caller wants to provide RAW Hmac-Secret SALT values directly. In that case, +// values if provided MUST be of WEBAUTHN_CTAP_ONE_HMAC_SECRET_LENGTH size. + +typedef struct _WEBAUTHN_HMAC_SECRET_SALT { + // Size of pbFirst. + DWORD cbFirst; + _Field_size_bytes_(cbFirst) + PBYTE pbFirst; // Required + + // Size of pbSecond. + DWORD cbSecond; + _Field_size_bytes_(cbSecond) + PBYTE pbSecond; +} WEBAUTHN_HMAC_SECRET_SALT, *PWEBAUTHN_HMAC_SECRET_SALT; +typedef const WEBAUTHN_HMAC_SECRET_SALT *PCWEBAUTHN_HMAC_SECRET_SALT; + +typedef struct _WEBAUTHN_CRED_WITH_HMAC_SECRET_SALT { + // Size of pbCredID. + DWORD cbCredID; + _Field_size_bytes_(cbCredID) + PBYTE pbCredID; // Required + + // PRF Values for above credential + PWEBAUTHN_HMAC_SECRET_SALT pHmacSecretSalt; // Required +} WEBAUTHN_CRED_WITH_HMAC_SECRET_SALT, *PWEBAUTHN_CRED_WITH_HMAC_SECRET_SALT; +typedef const WEBAUTHN_CRED_WITH_HMAC_SECRET_SALT *PCWEBAUTHN_CRED_WITH_HMAC_SECRET_SALT; + +typedef struct _WEBAUTHN_HMAC_SECRET_SALT_VALUES { + PWEBAUTHN_HMAC_SECRET_SALT pGlobalHmacSalt; + + DWORD cCredWithHmacSecretSaltList; + _Field_size_(cCredWithHmacSecretSaltList) + PWEBAUTHN_CRED_WITH_HMAC_SECRET_SALT pCredWithHmacSecretSaltList; +} WEBAUTHN_HMAC_SECRET_SALT_VALUES, *PWEBAUTHN_HMAC_SECRET_SALT_VALUES; +typedef const WEBAUTHN_HMAC_SECRET_SALT_VALUES *PCWEBAUTHN_HMAC_SECRET_SALT_VALUES; + +//+------------------------------------------------------------------------------------------ +// Hmac-Secret extension +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_EXTENSIONS_IDENTIFIER_HMAC_SECRET L"hmac-secret" +// Below type definitions is for WEBAUTHN_EXTENSIONS_IDENTIFIER_HMAC_SECRET +// MakeCredential Input Type: BOOL. +// - pvExtension must point to a BOOL with the value TRUE. +// - cbExtension must contain the sizeof(BOOL). +// MakeCredential Output Type: BOOL. +// - pvExtension will point to a BOOL with the value TRUE if credential +// was successfully created with HMAC_SECRET. +// - cbExtension will contain the sizeof(BOOL). +// GetAssertion Input Type: Not Supported +// GetAssertion Output Type: Not Supported + +//+------------------------------------------------------------------------------------------ +// credProtect extension +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_USER_VERIFICATION_ANY 0 +#define WEBAUTHN_USER_VERIFICATION_OPTIONAL 1 +#define WEBAUTHN_USER_VERIFICATION_OPTIONAL_WITH_CREDENTIAL_ID_LIST 2 +#define WEBAUTHN_USER_VERIFICATION_REQUIRED 3 + +typedef struct _WEBAUTHN_CRED_PROTECT_EXTENSION_IN { + // One of the above WEBAUTHN_USER_VERIFICATION_* values + DWORD dwCredProtect; + // Set the following to TRUE to require authenticator support for the credProtect extension + BOOL bRequireCredProtect; +} WEBAUTHN_CRED_PROTECT_EXTENSION_IN, *PWEBAUTHN_CRED_PROTECT_EXTENSION_IN; +typedef const WEBAUTHN_CRED_PROTECT_EXTENSION_IN *PCWEBAUTHN_CRED_PROTECT_EXTENSION_IN; + + +#define WEBAUTHN_EXTENSIONS_IDENTIFIER_CRED_PROTECT L"credProtect" +// Below type definitions is for WEBAUTHN_EXTENSIONS_IDENTIFIER_CRED_PROTECT +// MakeCredential Input Type: WEBAUTHN_CRED_PROTECT_EXTENSION_IN. +// - pvExtension must point to a WEBAUTHN_CRED_PROTECT_EXTENSION_IN struct +// - cbExtension will contain the sizeof(WEBAUTHN_CRED_PROTECT_EXTENSION_IN). +// MakeCredential Output Type: DWORD. +// - pvExtension will point to a DWORD with one of the above WEBAUTHN_USER_VERIFICATION_* values +// if credential was successfully created with CRED_PROTECT. +// - cbExtension will contain the sizeof(DWORD). +// GetAssertion Input Type: Not Supported +// GetAssertion Output Type: Not Supported + +//+------------------------------------------------------------------------------------------ +// credBlob extension +//------------------------------------------------------------------------------------------- + +typedef struct _WEBAUTHN_CRED_BLOB_EXTENSION { + // Size of pbCredBlob. + DWORD cbCredBlob; + _Field_size_bytes_(cbCredBlob) + PBYTE pbCredBlob; +} WEBAUTHN_CRED_BLOB_EXTENSION, *PWEBAUTHN_CRED_BLOB_EXTENSION; +typedef const WEBAUTHN_CRED_BLOB_EXTENSION *PCWEBAUTHN_CRED_BLOB_EXTENSION; + + +#define WEBAUTHN_EXTENSIONS_IDENTIFIER_CRED_BLOB L"credBlob" +// Below type definitions is for WEBAUTHN_EXTENSIONS_IDENTIFIER_CRED_BLOB +// MakeCredential Input Type: WEBAUTHN_CRED_BLOB_EXTENSION. +// - pvExtension must point to a WEBAUTHN_CRED_BLOB_EXTENSION struct +// - cbExtension must contain the sizeof(WEBAUTHN_CRED_BLOB_EXTENSION). +// MakeCredential Output Type: BOOL. +// - pvExtension will point to a BOOL with the value TRUE if credBlob was successfully created +// - cbExtension will contain the sizeof(BOOL). +// GetAssertion Input Type: BOOL. +// - pvExtension must point to a BOOL with the value TRUE to request the credBlob. +// - cbExtension must contain the sizeof(BOOL). +// GetAssertion Output Type: WEBAUTHN_CRED_BLOB_EXTENSION. +// - pvExtension will point to a WEBAUTHN_CRED_BLOB_EXTENSION struct if the authenticator +// returns the credBlob in the signed extensions +// - cbExtension will contain the sizeof(WEBAUTHN_CRED_BLOB_EXTENSION). + +//+------------------------------------------------------------------------------------------ +// minPinLength extension +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_EXTENSIONS_IDENTIFIER_MIN_PIN_LENGTH L"minPinLength" +// Below type definitions is for WEBAUTHN_EXTENSIONS_IDENTIFIER_MIN_PIN_LENGTH +// MakeCredential Input Type: BOOL. +// - pvExtension must point to a BOOL with the value TRUE to request the minPinLength. +// - cbExtension must contain the sizeof(BOOL). +// MakeCredential Output Type: DWORD. +// - pvExtension will point to a DWORD with the minimum pin length if returned by the authenticator +// - cbExtension will contain the sizeof(DWORD). +// GetAssertion Input Type: Not Supported +// GetAssertion Output Type: Not Supported + +//+------------------------------------------------------------------------------------------ +// Information about Extensions. +//------------------------------------------------------------------------------------------- +typedef struct _WEBAUTHN_EXTENSION { + LPCWSTR pwszExtensionIdentifier; + DWORD cbExtension; + PVOID pvExtension; +} WEBAUTHN_EXTENSION, *PWEBAUTHN_EXTENSION; +typedef const WEBAUTHN_EXTENSION *PCWEBAUTHN_EXTENSION; + +typedef struct _WEBAUTHN_EXTENSIONS { + DWORD cExtensions; + _Field_size_(cExtensions) + PWEBAUTHN_EXTENSION pExtensions; +} WEBAUTHN_EXTENSIONS, *PWEBAUTHN_EXTENSIONS; +typedef const WEBAUTHN_EXTENSIONS *PCWEBAUTHN_EXTENSIONS; + +//+------------------------------------------------------------------------------------------ +// Options. +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_AUTHENTICATOR_ATTACHMENT_ANY 0 +#define WEBAUTHN_AUTHENTICATOR_ATTACHMENT_PLATFORM 1 +#define WEBAUTHN_AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM 2 +#define WEBAUTHN_AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM_U2F_V2 3 + +#define WEBAUTHN_USER_VERIFICATION_REQUIREMENT_ANY 0 +#define WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED 1 +#define WEBAUTHN_USER_VERIFICATION_REQUIREMENT_PREFERRED 2 +#define WEBAUTHN_USER_VERIFICATION_REQUIREMENT_DISCOURAGED 3 + +#define WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_ANY 0 +#define WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_NONE 1 +#define WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_INDIRECT 2 +#define WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_DIRECT 3 + +#define WEBAUTHN_ENTERPRISE_ATTESTATION_NONE 0 +#define WEBAUTHN_ENTERPRISE_ATTESTATION_VENDOR_FACILITATED 1 +#define WEBAUTHN_ENTERPRISE_ATTESTATION_PLATFORM_MANAGED 2 + +#define WEBAUTHN_LARGE_BLOB_SUPPORT_NONE 0 +#define WEBAUTHN_LARGE_BLOB_SUPPORT_REQUIRED 1 +#define WEBAUTHN_LARGE_BLOB_SUPPORT_PREFERRED 2 + +#define WEBAUTHN_CREDENTIAL_HINT_SECURITY_KEY L"security-key" +#define WEBAUTHN_CREDENTIAL_HINT_CLIENT_DEVICE L"client-device" +#define WEBAUTHN_CREDENTIAL_HINT_HYBRID L"hybrid" + +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_1 1 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_2 2 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_3 3 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_4 4 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_5 5 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_6 6 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_7 7 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_8 8 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_9 9 +#define WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_CURRENT_VERSION WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_9 + +typedef struct _WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Time that the operation is expected to complete within. + // This is used as guidance, and can be overridden by the platform. + DWORD dwTimeoutMilliseconds; + + // Credentials used for exclusion. + WEBAUTHN_CREDENTIALS CredentialList; + + // Optional extensions to parse when performing the operation. + WEBAUTHN_EXTENSIONS Extensions; + + // Optional. Platform vs Cross-Platform Authenticators. + DWORD dwAuthenticatorAttachment; + + // Optional. Require key to be resident or not. Defaulting to FALSE. + BOOL bRequireResidentKey; + + // User Verification Requirement. + DWORD dwUserVerificationRequirement; + + // Attestation Conveyance Preference. + DWORD dwAttestationConveyancePreference; + + // Reserved for future Use + DWORD dwFlags; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_2 + // + + // Cancellation Id - Optional - See WebAuthNGetCancellationId + GUID *pCancellationId; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_3 + // + + // Exclude Credential List. If present, "CredentialList" will be ignored. + PWEBAUTHN_CREDENTIAL_LIST pExcludeCredentialList; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_4 + // + + // Enterprise Attestation + DWORD dwEnterpriseAttestation; + + // Large Blob Support: none, required or preferred + // + // NTE_INVALID_PARAMETER when large blob required or preferred and + // bRequireResidentKey isn't set to TRUE + DWORD dwLargeBlobSupport; + + // Optional. Prefer key to be resident. Defaulting to FALSE. When TRUE, + // overrides the above bRequireResidentKey. + BOOL bPreferResidentKey; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_5 + // + + // Optional. BrowserInPrivate Mode. Defaulting to FALSE. + BOOL bBrowserInPrivateMode; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_6 + // + + // Enable PRF + BOOL bEnablePrf; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_7 + // + + // Deprecated + // Optional. Linked Device Connection Info. + PCTAPCBOR_HYBRID_STORAGE_LINKED_DATA pLinkedDevice; + + // Size of pbJsonExt + DWORD cbJsonExt; + _Field_size_bytes_(cbJsonExt) + PBYTE pbJsonExt; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_8 + // + + // PRF extension "eval" values which will be converted into HMAC-SECRET values according to WebAuthn Spec. + // Set WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG in dwFlags above, if caller wants to provide RAW Hmac-Secret SALT values directly. + // In that case, values provided MUST be of WEBAUTHN_CTAP_ONE_HMAC_SECRET_LENGTH size. + PWEBAUTHN_HMAC_SECRET_SALT pPRFGlobalEval; + + // PublicKeyCredentialHints (https://w3c.github.io/webauthn/#enum-hints) + DWORD cCredentialHints; + _Field_size_(cCredentialHints) + LPCWSTR *ppwszCredentialHints; + + // Enable ThirdPartyPayment + BOOL bThirdPartyPayment; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS_VERSION_9 + // + + // Web Origin. For Remote Web App scenario. + PCWSTR pwszRemoteWebOrigin; + + // UTF-8 encoded JSON serialization of the PublicKeyCredentialCreationOptions. + DWORD cbPublicKeyCredentialCreationOptionsJSON; + _Field_size_bytes_(cbPublicKeyCredentialCreationOptionsJSON) + PBYTE pbPublicKeyCredentialCreationOptionsJSON; + + // Authenticator ID got from WebAuthNGetAuthenticatorList API. + DWORD cbAuthenticatorId; + _Field_size_bytes_(cbAuthenticatorId) + PBYTE pbAuthenticatorId; + +} WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS, *PWEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS; +typedef const WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS *PCWEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS; + +#define WEBAUTHN_CRED_LARGE_BLOB_OPERATION_NONE 0 +#define WEBAUTHN_CRED_LARGE_BLOB_OPERATION_GET 1 +#define WEBAUTHN_CRED_LARGE_BLOB_OPERATION_SET 2 +#define WEBAUTHN_CRED_LARGE_BLOB_OPERATION_DELETE 3 + +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_1 1 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_2 2 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_3 3 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_4 4 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_5 5 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_6 6 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_7 7 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_8 8 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_9 9 +#define WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_CURRENT_VERSION WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_9 + +/* + Information about flags. +*/ + +#define WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG 0x00100000 + +typedef struct _WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Time that the operation is expected to complete within. + // This is used as guidance, and can be overridden by the platform. + DWORD dwTimeoutMilliseconds; + + // Allowed Credentials List. + WEBAUTHN_CREDENTIALS CredentialList; + + // Optional extensions to parse when performing the operation. + WEBAUTHN_EXTENSIONS Extensions; + + // Optional. Platform vs Cross-Platform Authenticators. + DWORD dwAuthenticatorAttachment; + + // User Verification Requirement. + DWORD dwUserVerificationRequirement; + + // Flags + DWORD dwFlags; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_2 + // + + // Optional identifier for the U2F AppId. Converted to UTF8 before being hashed. Not lower cased. + PCWSTR pwszU2fAppId; + + // If the following is non-NULL, then, set to TRUE if the above pwszU2fAppid was used instead of + // PCWSTR pwszRpId; + BOOL *pbU2fAppId; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_3 + // + + // Cancellation Id - Optional - See WebAuthNGetCancellationId + GUID *pCancellationId; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_4 + // + + // Allow Credential List. If present, "CredentialList" will be ignored. + PWEBAUTHN_CREDENTIAL_LIST pAllowCredentialList; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_5 + // + + DWORD dwCredLargeBlobOperation; + + // Size of pbCredLargeBlob + DWORD cbCredLargeBlob; + _Field_size_bytes_(cbCredLargeBlob) + PBYTE pbCredLargeBlob; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_6 + // + + // PRF values which will be converted into HMAC-SECRET values according to WebAuthn Spec. + PWEBAUTHN_HMAC_SECRET_SALT_VALUES pHmacSecretSaltValues; + + // Optional. BrowserInPrivate Mode. Defaulting to FALSE. + BOOL bBrowserInPrivateMode; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_7 + // + + // Deprecated + // Optional. Linked Device Connection Info. + PCTAPCBOR_HYBRID_STORAGE_LINKED_DATA pLinkedDevice; + + // Optional. Allowlist MUST contain 1 credential applicable for Hybrid transport. + BOOL bAutoFill; + + // Size of pbJsonExt + DWORD cbJsonExt; + _Field_size_bytes_(cbJsonExt) + PBYTE pbJsonExt; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_8 + // + + // PublicKeyCredentialHints (https://w3c.github.io/webauthn/#enum-hints) + DWORD cCredentialHints; + _Field_size_(cCredentialHints) + LPCWSTR *ppwszCredentialHints; + + // + // The following fields have been added in WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS_VERSION_9 + // + + // Web Origin. For Remote Web App scenario. + PCWSTR pwszRemoteWebOrigin; + + // UTF-8 encoded JSON serialization of the PublicKeyCredentialRequestOptions. + DWORD cbPublicKeyCredentialRequestOptionsJSON; + _Field_size_bytes_(cbPublicKeyCredentialRequestOptionsJSON) + PBYTE pbPublicKeyCredentialRequestOptionsJSON; + + // Authenticator ID got from WebAuthNGetAuthenticatorList API. + DWORD cbAuthenticatorId; + _Field_size_bytes_(cbAuthenticatorId) + PBYTE pbAuthenticatorId; + +} WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS, *PWEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS; +typedef const WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS *PCWEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS; + + +//+------------------------------------------------------------------------------------------ +// Attestation Info. +// +//------------------------------------------------------------------------------------------- +#define WEBAUTHN_ATTESTATION_DECODE_NONE 0 +#define WEBAUTHN_ATTESTATION_DECODE_COMMON 1 +// WEBAUTHN_ATTESTATION_DECODE_COMMON supports format types +// L"packed" +// L"fido-u2f" + +#define WEBAUTHN_ATTESTATION_VER_TPM_2_0 L"2.0" + +typedef struct _WEBAUTHN_X5C { + // Length of X.509 encoded certificate + DWORD cbData; + // X.509 encoded certificate bytes + _Field_size_bytes_(cbData) + PBYTE pbData; +} WEBAUTHN_X5C, *PWEBAUTHN_X5C; + +// Supports either Self or Full Basic Attestation + +// Note, new fields will be added to the following data structure to +// support additional attestation format types, such as, TPM. +// When fields are added, the dwVersion will be incremented. +// +// Therefore, your code must make the following check: +// "if (dwVersion >= WEBAUTHN_COMMON_ATTESTATION_CURRENT_VERSION)" + +#define WEBAUTHN_COMMON_ATTESTATION_CURRENT_VERSION 1 + +typedef struct _WEBAUTHN_COMMON_ATTESTATION { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Hash and Padding Algorithm + // + // The following won't be set for "fido-u2f" which assumes "ES256". + PCWSTR pwszAlg; + LONG lAlg; // COSE algorithm + + // Signature that was generated for this attestation. + DWORD cbSignature; + _Field_size_bytes_(cbSignature) + PBYTE pbSignature; + + // Following is set for Full Basic Attestation. If not, set then, this is Self Attestation. + // Array of X.509 DER encoded certificates. The first certificate is the signer, leaf certificate. + DWORD cX5c; + _Field_size_(cX5c) + PWEBAUTHN_X5C pX5c; + + // Following are also set for tpm + PCWSTR pwszVer; // L"2.0" + DWORD cbCertInfo; + _Field_size_bytes_(cbCertInfo) + PBYTE pbCertInfo; + DWORD cbPubArea; + _Field_size_bytes_(cbPubArea) + PBYTE pbPubArea; +} WEBAUTHN_COMMON_ATTESTATION, *PWEBAUTHN_COMMON_ATTESTATION; +typedef const WEBAUTHN_COMMON_ATTESTATION *PCWEBAUTHN_COMMON_ATTESTATION; + +#define WEBAUTHN_ATTESTATION_TYPE_PACKED L"packed" +#define WEBAUTHN_ATTESTATION_TYPE_U2F L"fido-u2f" +#define WEBAUTHN_ATTESTATION_TYPE_TPM L"tpm" +#define WEBAUTHN_ATTESTATION_TYPE_NONE L"none" + +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_1 1 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_2 2 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_3 3 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_4 4 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_5 5 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_6 6 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_7 7 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_8 8 +#define WEBAUTHN_CREDENTIAL_ATTESTATION_CURRENT_VERSION WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_8 + +typedef struct _WEBAUTHN_CREDENTIAL_ATTESTATION { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Attestation format type + PCWSTR pwszFormatType; + + // Size of cbAuthenticatorData. + DWORD cbAuthenticatorData; + // Authenticator data that was created for this credential. + _Field_size_bytes_(cbAuthenticatorData) + PBYTE pbAuthenticatorData; + + // Size of CBOR encoded attestation information + //0 => encoded as CBOR null value. + DWORD cbAttestation; + //Encoded CBOR attestation information + _Field_size_bytes_(cbAttestation) + PBYTE pbAttestation; + + DWORD dwAttestationDecodeType; + // Following depends on the dwAttestationDecodeType + // WEBAUTHN_ATTESTATION_DECODE_NONE + // NULL - not able to decode the CBOR attestation information + // WEBAUTHN_ATTESTATION_DECODE_COMMON + // PWEBAUTHN_COMMON_ATTESTATION; + PVOID pvAttestationDecode; + + // The CBOR encoded Attestation Object to be returned to the RP. + DWORD cbAttestationObject; + _Field_size_bytes_(cbAttestationObject) + PBYTE pbAttestationObject; + + // The CredentialId bytes extracted from the Authenticator Data. + // Used by Edge to return to the RP. + DWORD cbCredentialId; + _Field_size_bytes_(cbCredentialId) + PBYTE pbCredentialId; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_2 + // + + WEBAUTHN_EXTENSIONS Extensions; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_3 + // + + // One of the WEBAUTHN_CTAP_TRANSPORT_* bits will be set corresponding to + // the transport that was used. + DWORD dwUsedTransport; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_4 + // + + BOOL bEpAtt; + BOOL bLargeBlobSupported; + BOOL bResidentKey; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_5 + // + + BOOL bPrfEnabled; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_6 + // + + DWORD cbUnsignedExtensionOutputs; + _Field_size_bytes_(cbUnsignedExtensionOutputs) + PBYTE pbUnsignedExtensionOutputs; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_7 + // + + PWEBAUTHN_HMAC_SECRET_SALT pHmacSecret; + + // ThirdPartyPayment Credential or not. + BOOL bThirdPartyPayment; + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_8 + // + + // Multiple WEBAUTHN_CTAP_TRANSPORT_* bits will be set corresponding to + // the transports that are supported. + DWORD dwTransports; + + // UTF-8 encoded JSON serialization of the client data. + DWORD cbClientDataJSON; + _Field_size_bytes_(cbClientDataJSON) + PBYTE pbClientDataJSON; + + // UTF-8 encoded JSON serialization of the RegistrationResponse. + DWORD cbRegistrationResponseJSON; + _Field_size_bytes_(cbRegistrationResponseJSON) + PBYTE pbRegistrationResponseJSON; + +} WEBAUTHN_CREDENTIAL_ATTESTATION, *PWEBAUTHN_CREDENTIAL_ATTESTATION; +typedef const WEBAUTHN_CREDENTIAL_ATTESTATION *PCWEBAUTHN_CREDENTIAL_ATTESTATION; + + +//+------------------------------------------------------------------------------------------ +// authenticatorGetAssertion output. +//------------------------------------------------------------------------------------------- + +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_NONE 0 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_SUCCESS 1 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_NOT_SUPPORTED 2 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_INVALID_DATA 3 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_INVALID_PARAMETER 4 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_NOT_FOUND 5 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_MULTIPLE_CREDENTIALS 6 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_LACK_OF_SPACE 7 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_PLATFORM_ERROR 8 +#define WEBAUTHN_CRED_LARGE_BLOB_STATUS_AUTHENTICATOR_ERROR 9 + +#define WEBAUTHN_ASSERTION_VERSION_1 1 +#define WEBAUTHN_ASSERTION_VERSION_2 2 +#define WEBAUTHN_ASSERTION_VERSION_3 3 +#define WEBAUTHN_ASSERTION_VERSION_4 4 +#define WEBAUTHN_ASSERTION_VERSION_5 5 +#define WEBAUTHN_ASSERTION_VERSION_6 6 +#define WEBAUTHN_ASSERTION_CURRENT_VERSION WEBAUTHN_ASSERTION_VERSION_6 + +typedef struct _WEBAUTHN_ASSERTION { + // Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Size of cbAuthenticatorData. + DWORD cbAuthenticatorData; + // Authenticator data that was created for this assertion. + _Field_size_bytes_(cbAuthenticatorData) + PBYTE pbAuthenticatorData; + + // Size of pbSignature. + DWORD cbSignature; + // Signature that was generated for this assertion. + _Field_size_bytes_(cbSignature) + PBYTE pbSignature; + + // Credential that was used for this assertion. + WEBAUTHN_CREDENTIAL Credential; + + // Size of User Id + DWORD cbUserId; + // UserId + _Field_size_bytes_(cbUserId) + PBYTE pbUserId; + + // + // Following fields have been added in WEBAUTHN_ASSERTION_VERSION_2 + // + + WEBAUTHN_EXTENSIONS Extensions; + + // Size of pbCredLargeBlob + DWORD cbCredLargeBlob; + _Field_size_bytes_(cbCredLargeBlob) + PBYTE pbCredLargeBlob; + + DWORD dwCredLargeBlobStatus; + + // + // Following fields have been added in WEBAUTHN_ASSERTION_VERSION_3 + // + + PWEBAUTHN_HMAC_SECRET_SALT pHmacSecret; + + // + // Following fields have been added in WEBAUTHN_ASSERTION_VERSION_4 + // + + // One of the WEBAUTHN_CTAP_TRANSPORT_* bits will be set corresponding to + // the transport that was used. + DWORD dwUsedTransport; + + // + // Following fields have been added in WEBAUTHN_ASSERTION_VERSION_5 + // + + DWORD cbUnsignedExtensionOutputs; + _Field_size_bytes_(cbUnsignedExtensionOutputs) + PBYTE pbUnsignedExtensionOutputs; + + // + // Following fields have been added in WEBAUTHN_ASSERTION_VERSION_6 + // + + // UTF-8 encoded JSON serialization of the client data. + DWORD cbClientDataJSON; + _Field_size_bytes_(cbClientDataJSON) + PBYTE pbClientDataJSON; + + // UTF-8 encoded JSON serialization of the AuthenticationResponse. + DWORD cbAuthenticationResponseJSON; + _Field_size_bytes_(cbAuthenticationResponseJSON) + PBYTE pbAuthenticationResponseJSON; + +} WEBAUTHN_ASSERTION, *PWEBAUTHN_ASSERTION; +typedef const WEBAUTHN_ASSERTION *PCWEBAUTHN_ASSERTION; + +//+------------------------------------------------------------------------------------------ +// APIs. +//------------------------------------------------------------------------------------------- + +DWORD +WINAPI +WebAuthNGetApiVersionNumber(); + +HRESULT +WINAPI +WebAuthNIsUserVerifyingPlatformAuthenticatorAvailable( + _Out_ BOOL *pbIsUserVerifyingPlatformAuthenticatorAvailable); + + +HRESULT +WINAPI +WebAuthNAuthenticatorMakeCredential( + _In_ HWND hWnd, + _In_ PCWEBAUTHN_RP_ENTITY_INFORMATION pRpInformation, + _In_ PCWEBAUTHN_USER_ENTITY_INFORMATION pUserInformation, + _In_ PCWEBAUTHN_COSE_CREDENTIAL_PARAMETERS pPubKeyCredParams, + _In_ PCWEBAUTHN_CLIENT_DATA pWebAuthNClientData, + _In_opt_ PCWEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS pWebAuthNMakeCredentialOptions, + _Outptr_result_maybenull_ PWEBAUTHN_CREDENTIAL_ATTESTATION *ppWebAuthNCredentialAttestation); + + +HRESULT +WINAPI +WebAuthNAuthenticatorGetAssertion( + _In_ HWND hWnd, + _In_ LPCWSTR pwszRpId, + _In_ PCWEBAUTHN_CLIENT_DATA pWebAuthNClientData, + _In_opt_ PCWEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS pWebAuthNGetAssertionOptions, + _Outptr_result_maybenull_ PWEBAUTHN_ASSERTION *ppWebAuthNAssertion); + +void +WINAPI +WebAuthNFreeCredentialAttestation( + _In_opt_ PWEBAUTHN_CREDENTIAL_ATTESTATION pWebAuthNCredentialAttestation); + +void +WINAPI +WebAuthNFreeAssertion( + _In_ PWEBAUTHN_ASSERTION pWebAuthNAssertion); + +HRESULT +WINAPI +WebAuthNGetCancellationId( + _Out_ GUID* pCancellationId); + +HRESULT +WINAPI +WebAuthNCancelCurrentOperation( + _In_ const GUID* pCancellationId); + +// Returns NTE_NOT_FOUND when credentials are not found. +HRESULT +WINAPI +WebAuthNGetPlatformCredentialList( + _In_ PCWEBAUTHN_GET_CREDENTIALS_OPTIONS pGetCredentialsOptions, + _Outptr_result_maybenull_ PWEBAUTHN_CREDENTIAL_DETAILS_LIST *ppCredentialDetailsList); + +void +WINAPI +WebAuthNFreePlatformCredentialList( + _In_ PWEBAUTHN_CREDENTIAL_DETAILS_LIST pCredentialDetailsList); + +HRESULT +WINAPI +WebAuthNDeletePlatformCredential( + _In_ DWORD cbCredentialId, + _In_reads_bytes_(cbCredentialId) const BYTE *pbCredentialId + ); + +// Returns NTE_NOT_FOUND when authenticator details are not found. +HRESULT +WINAPI +WebAuthNGetAuthenticatorList( + _In_opt_ PCWEBAUTHN_AUTHENTICATOR_DETAILS_OPTIONS pWebAuthNGetAuthenticatorListOptions, + _Outptr_result_maybenull_ PWEBAUTHN_AUTHENTICATOR_DETAILS_LIST* ppAuthenticatorDetailsList); + +void +WINAPI +WebAuthNFreeAuthenticatorList( + _In_ PWEBAUTHN_AUTHENTICATOR_DETAILS_LIST pAuthenticatorDetailsList); + +// +// Returns the following Error Names: +// L"Success" - S_OK +// L"InvalidStateError" - NTE_EXISTS +// L"ConstraintError" - HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED), +// NTE_NOT_SUPPORTED, +// NTE_TOKEN_KEYSET_STORAGE_FULL +// L"NotSupportedError" - NTE_INVALID_PARAMETER +// L"NotAllowedError" - NTE_DEVICE_NOT_FOUND, +// NTE_NOT_FOUND, +// HRESULT_FROM_WIN32(ERROR_CANCELLED), +// NTE_USER_CANCELLED, +// HRESULT_FROM_WIN32(ERROR_TIMEOUT) +// L"UnknownError" - All other hr values +// +PCWSTR +WINAPI +WebAuthNGetErrorName( + _In_ HRESULT hr); + +HRESULT +WINAPI +WebAuthNGetW3CExceptionDOMError( + _In_ HRESULT hr); + + +#ifdef __cplusplus +} // Balance extern "C" above +#endif + +#endif // WINAPI_FAMILY_PARTITION +#pragma endregion + +#endif // __WEBAUTHN_H_ diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthnplugin.h b/apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthnplugin.h new file mode 100644 index 00000000000..bffd2049187 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/include/webauthnplugin.h @@ -0,0 +1,588 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include + +#pragma region Desktop Family or OneCore Family +#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_SYSTEM) + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef WINAPI +#define WINAPI __stdcall +#endif + +#ifndef INITGUID +#define INITGUID +#include +#undef INITGUID +#else +#include +#endif + +//+------------------------------------------------------------------------------------------ +// APIs. +//------------------------------------------------------------------------------------------- + +typedef enum _PLUGIN_AUTHENTICATOR_STATE +{ + AuthenticatorState_Disabled = 0, + AuthenticatorState_Enabled +} AUTHENTICATOR_STATE; + +HRESULT +WINAPI +WebAuthNPluginGetAuthenticatorState( + _In_ REFCLSID rclsid, + _Out_ AUTHENTICATOR_STATE* pluginAuthenticatorState +); + +// +// Plugin Authenticator API: WebAuthNAddPluginAuthenticator: Add Plugin Authenticator +// + +typedef struct _WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS { + // Authenticator Name + LPCWSTR pwszAuthenticatorName; + + // Plugin COM ClsId + REFCLSID rclsid; + + // Plugin RPID (Optional. Required for a nested WebAuthN call originating from a plugin) + LPCWSTR pwszPluginRpId; + + // Plugin Authenticator Logo for the Light themes. base64 encoded SVG 1.1 (Optional) + LPCWSTR pwszLightThemeLogoSvg; + + // Plugin Authenticator Logo for the Dark themes. base64 encoded SVG 1.1 (Optional) + LPCWSTR pwszDarkThemeLogoSvg; + + // CTAP CBOR encoded authenticatorGetInfo + DWORD cbAuthenticatorInfo; + _Field_size_bytes_(cbAuthenticatorInfo) + const BYTE* pbAuthenticatorInfo; + + // List of supported RP IDs (Relying Party IDs). Should be 0/nullptr if all RPs are supported. + DWORD cSupportedRpIds; + const LPCWSTR* ppwszSupportedRpIds; + +} WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS, *PWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS; +typedef const WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS *PCWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS; + +typedef struct _WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE { + // Plugin operation signing Public Key - Used to sign the request in PCWEBAUTHN_PLUGIN_OPERATION_REQUEST. Refer pluginauthenticator.h. + DWORD cbOpSignPubKey; + _Field_size_bytes_(cbOpSignPubKey) + PBYTE pbOpSignPubKey; + +} WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE, *PWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE; +typedef const WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE *PCWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE; + +HRESULT +WINAPI +WebAuthNPluginAddAuthenticator( + _In_ PCWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS pPluginAddAuthenticatorOptions, + _Outptr_result_maybenull_ PWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE* ppPluginAddAuthenticatorResponse); + +void +WINAPI +WebAuthNPluginFreeAddAuthenticatorResponse( + _In_opt_ PWEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE pPluginAddAuthenticatorResponse); + +// +// Plugin Authenticator API: WebAuthNRemovePluginAuthenticator: Remove Plugin Authenticator +// + +HRESULT +WINAPI +WebAuthNPluginRemoveAuthenticator( + _In_ REFCLSID rclsid); + +// +// Plugin Authenticator API: WebAuthNPluginAuthenticatorUpdateDetails: Update Credential Metadata for Browser AutoFill Scenarios +// + +typedef struct _WEBAUTHN_PLUGIN_UPDATE_AUTHENTICATOR_DETAILS { + // Authenticator Name (Optional) + LPCWSTR pwszAuthenticatorName; + + // Plugin COM ClsId + REFCLSID rclsid; + + // New Plugin COM ClsId (Optional) + REFCLSID rclsidNew; + + // Plugin Authenticator Logo for the Light themes. base64 encoded SVG 1.1 (Optional) + LPCWSTR pwszLightThemeLogoSvg; + + // Plugin Authenticator Logo for the Dark themes. base64 encoded SVG 1.1 (Optional) + LPCWSTR pwszDarkThemeLogoSvg; + + // CTAP CBOR encoded authenticatorGetInfo + DWORD cbAuthenticatorInfo; + _Field_size_bytes_(cbAuthenticatorInfo) + const BYTE* pbAuthenticatorInfo; + + // List of supported RP IDs (Relying Party IDs). Should be 0/nullptr if all RPs are supported. + DWORD cSupportedRpIds; + const LPCWSTR* ppwszSupportedRpIds; + +} WEBAUTHN_PLUGIN_UPDATE_AUTHENTICATOR_DETAILS, *PWEBAUTHN_PLUGIN_UPDATE_AUTHENTICATOR_DETAILS; +typedef const WEBAUTHN_PLUGIN_UPDATE_AUTHENTICATOR_DETAILS *PCWEBAUTHN_PLUGIN_UPDATE_AUTHENTICATOR_DETAILS; + +HRESULT +WINAPI +WebAuthNPluginUpdateAuthenticatorDetails( + _In_ PCWEBAUTHN_PLUGIN_UPDATE_AUTHENTICATOR_DETAILS pPluginUpdateAuthenticatorDetails); + +// +// Plugin Authenticator API: WebAuthNPluginAuthenticatorAddCredentials: Add Credential Metadata for Browser AutoFill Scenarios +// + +typedef struct _WEBAUTHN_PLUGIN_CREDENTIAL_DETAILS { + // Size of pbCredentialId. + DWORD cbCredentialId; + + // Credential Identifier bytes. This field is required. + _Field_size_bytes_(cbCredentialId) + const BYTE* pbCredentialId; + + // Identifier for the RP. This field is required. + LPCWSTR pwszRpId; + + // Contains the friendly name of the Relying Party, such as "Acme Corporation", "Widgets Inc" or "Awesome Site". + // This field is required. + LPCWSTR pwszRpName; + + // Identifier for the User. This field is required. + DWORD cbUserId; + + // User Identifier bytes. This field is required. + _Field_size_bytes_(cbUserId) + const BYTE* pbUserId; + + // Contains a detailed name for this account, such as "john.p.smith@example.com". + LPCWSTR pwszUserName; + + // For User: Contains the friendly name associated with the user account such as "John P. Smith". + LPCWSTR pwszUserDisplayName; + +} WEBAUTHN_PLUGIN_CREDENTIAL_DETAILS, *PWEBAUTHN_PLUGIN_CREDENTIAL_DETAILS; +typedef const WEBAUTHN_PLUGIN_CREDENTIAL_DETAILS *PCWEBAUTHN_PLUGIN_CREDENTIAL_DETAILS; + +HRESULT +WINAPI +WebAuthNPluginAuthenticatorAddCredentials( + _In_ REFCLSID rclsid, + _In_ DWORD cCredentialDetails, + _In_reads_(cCredentialDetails) PCWEBAUTHN_PLUGIN_CREDENTIAL_DETAILS pCredentialDetails); + +// +// Plugin Authenticator API: WebAuthNPluginAuthenticatorRemoveCredentials: Remove Credential Metadata for Browser AutoFill Scenarios +// + +HRESULT +WINAPI +WebAuthNPluginAuthenticatorRemoveCredentials( + _In_ REFCLSID rclsid, + _In_ DWORD cCredentialDetails, + _In_reads_(cCredentialDetails) PCWEBAUTHN_PLUGIN_CREDENTIAL_DETAILS pCredentialDetails); + +// +// Plugin Authenticator API: WebAuthNPluginAuthenticatorRemoveCredentials: Remove All Credential Metadata for Browser AutoFill Scenarios +// + +HRESULT +WINAPI +WebAuthNPluginAuthenticatorRemoveAllCredentials( + _In_ REFCLSID rclsid); + +// +// Plugin Authenticator API: WebAuthNPluginAuthenticatorGetAllCredentials: Get All Credential Metadata cached for Browser AutoFill Scenarios +// + +HRESULT +WINAPI +WebAuthNPluginAuthenticatorGetAllCredentials( + _In_ REFCLSID rclsid, + _Out_ DWORD* pcCredentialDetails, + _Outptr_result_buffer_maybenull_(*pcCredentialDetails) PWEBAUTHN_PLUGIN_CREDENTIAL_DETAILS* ppCredentialDetailsArray); + +// +// Plugin Authenticator API: WebAuthNPluginAuthenticatorFreeCredentialDetailsList: Free Credential Metadata cached for Browser AutoFill Scenarios +// + +void +WINAPI +WebAuthNPluginAuthenticatorFreeCredentialDetailsArray( + _In_ DWORD cCredentialDetails, + _In_reads_(cCredentialDetails) PWEBAUTHN_PLUGIN_CREDENTIAL_DETAILS pCredentialDetailsArray); + +// +// Hello UV API for Plugin: WebAuthNPluginPerformUv: Perform Hello UV related operations +// + +typedef enum _WEBAUTHN_PLUGIN_PERFORM_UV_OPERATION_TYPE +{ + PerformUserVerification = 1, + GetUserVerificationCount, + GetPublicKey +} WEBAUTHN_PLUGIN_PERFORM_UV_OPERATION_TYPE; + +typedef struct _WEBAUTHN_PLUGIN_USER_VERIFICATION_REQUEST { + + // Windows handle of the top-level window displayed by the plugin and currently is in foreground as part of the ongoing webauthn operation. + HWND hwnd; + + // The webauthn transaction id from the WEBAUTHN_PLUGIN_OPERATION_REQUEST + REFGUID rguidTransactionId; + + // The username attached to the credential that is in use for this webauthn operation + LPCWSTR pwszUsername; + + // A text hint displayed on the windows hello prompt + LPCWSTR pwszDisplayHint; +} WEBAUTHN_PLUGIN_USER_VERIFICATION_REQUEST, *PWEBAUTHN_PLUGIN_USER_VERIFICATION_REQUEST; +typedef const WEBAUTHN_PLUGIN_USER_VERIFICATION_REQUEST *PCWEBAUTHN_PLUGIN_USER_VERIFICATION_REQUEST; + +HRESULT +WINAPI +WebAuthNPluginPerformUserVerification( + _In_ PCWEBAUTHN_PLUGIN_USER_VERIFICATION_REQUEST pPluginUserVerification, + _Out_ DWORD* pcbResponse, + _Outptr_result_bytebuffer_maybenull_(*pcbResponse) PBYTE* ppbResponse); + +void +WINAPI +WebAuthNPluginFreeUserVerificationResponse( + _In_opt_ PBYTE ppbResponse); + +HRESULT +WINAPI +WebAuthNPluginGetUserVerificationCount( + _In_ REFCLSID rclsid, + _Out_ DWORD* pdwVerificationCount); + +HRESULT +WINAPI +WebAuthNPluginGetUserVerificationPublicKey( + _In_ REFCLSID rclsid, + _Out_ DWORD* pcbPublicKey, + _Outptr_result_bytebuffer_(*pcbPublicKey) PBYTE* ppbPublicKey); // Free using WebAuthNPluginFreePublicKeyResponse + +HRESULT +WINAPI +WebAuthNPluginGetOperationSigningPublicKey( + _In_ REFCLSID rclsid, + _Out_ DWORD* pcbOpSignPubKey, + _Outptr_result_buffer_maybenull_(*pcbOpSignPubKey) PBYTE* ppbOpSignPubKey); // Free using WebAuthNPluginFreePublicKeyResponse + +void WINAPI WebAuthNPluginFreePublicKeyResponse( + _In_opt_ PBYTE pbOpSignPubKey); + +#define WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS_VERSION_1 1 +#define WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS_CURRENT_VERSION WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS_VERSION_1 +typedef struct _WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS { + //Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Following have following values: + // +1 - TRUE + // 0 - Not defined + // -1 - FALSE + //up: "true" | "false" + LONG lUp; + //uv: "true" | "false" + LONG lUv; + //rk: "true" | "false" + LONG lRequireResidentKey; +} WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS, *PWEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS; +typedef const WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS *PCWEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS; + +#define WEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY_VERSION_1 1 +#define WEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY_CURRENT_VERSION WEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY_VERSION_1 +typedef struct _WEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY { + //Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Key type + LONG lKty; + + // Hash Algorithm: ES256, ES384, ES512 + LONG lAlg; + + // Curve + LONG lCrv; + + //Size of "x" (X Coordinate) + DWORD cbX; + + //"x" (X Coordinate) data. Big Endian. + PBYTE pbX; + + //Size of "y" (Y Coordinate) + DWORD cbY; + + //"y" (Y Coordinate) data. Big Endian. + PBYTE pbY; +} WEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY, *PWEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY; +typedef const WEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY *PCWEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY; + +#define WEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION_VERSION_1 1 +#define WEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION_CURRENT_VERSION WEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION_VERSION_1 +typedef struct _WEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION { + //Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + // Platform's key agreement public key + PWEBAUTHN_CTAPCBOR_ECC_PUBLIC_KEY pKeyAgreement; + + DWORD cbEncryptedSalt; + PBYTE pbEncryptedSalt; + + DWORD cbSaltAuth; + PBYTE pbSaltAuth; +} WEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION, *PWEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION; +typedef const WEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION *PCWEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION; + +#define WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST_VERSION_1 1 +#define WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST_CURRENT_VERSION WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST_VERSION_1 +typedef struct _WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST { + //Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + //Input RP ID. Raw UTF8 bytes before conversion. + //These are the bytes to be hashed in the Authenticator Data. + DWORD cbRpId; + PBYTE pbRpId; + + //Client Data Hash + DWORD cbClientDataHash; + PBYTE pbClientDataHash; + + //RP Information + PCWEBAUTHN_RP_ENTITY_INFORMATION pRpInformation; + + //User Information + PCWEBAUTHN_USER_ENTITY_INFORMATION pUserInformation; + + // Crypto Parameters + WEBAUTHN_COSE_CREDENTIAL_PARAMETERS WebAuthNCredentialParameters; + + //Credentials used for exclusion + WEBAUTHN_CREDENTIAL_LIST CredentialList; + + //Optional extensions to parse when performing the operation. + DWORD cbCborExtensionsMap; + PBYTE pbCborExtensionsMap; + + // Authenticator Options (Optional) + PWEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS pAuthenticatorOptions; + + // Pin Auth (Optional) + BOOL fEmptyPinAuth; // Zero length PinAuth is included in the request + DWORD cbPinAuth; + PBYTE pbPinAuth; + + //"hmac-secret": true extension + LONG lHmacSecretExt; + + // "hmac-secret-mc" extension + PWEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION pHmacSecretMcExtension; + + //"prf" extension + LONG lPrfExt; + DWORD cbHmacSecretSaltValues; + PBYTE pbHmacSecretSaltValues; + + //"credProtect" extension. Nonzero if present + DWORD dwCredProtect; + + // Nonzero if present + DWORD dwPinProtocol; + + // Nonzero if present + DWORD dwEnterpriseAttestation; + + //"credBlob" extension. Nonzero if present + DWORD cbCredBlobExt; + PBYTE pbCredBlobExt; + + //"largeBlobKey": true extension + LONG lLargeBlobKeyExt; + + //"largeBlob": extension + DWORD dwLargeBlobSupport; + + //"minPinLength": true extension + LONG lMinPinLengthExt; + + // "json" extension. Nonzero if present + DWORD cbJsonExt; + PBYTE pbJsonExt; +} WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST, *PWEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST; +typedef const WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST *PCWEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST; + +_Success_(return == S_OK) +HRESULT +WINAPI +WebAuthNEncodeMakeCredentialResponse( + _In_ PCWEBAUTHN_CREDENTIAL_ATTESTATION pCredentialAttestation, + _Out_ DWORD* pcbResp, + _Outptr_result_buffer_maybenull_(*pcbResp) BYTE** ppbResp + ); + +_Success_(return == S_OK) +HRESULT +WINAPI +WebAuthNDecodeMakeCredentialRequest( + _In_ DWORD cbEncoded, + _In_reads_bytes_(cbEncoded) const BYTE* pbEncoded, + _Outptr_ PWEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST* ppMakeCredentialRequest + ); + +void +WINAPI +WebAuthNFreeDecodedMakeCredentialRequest( + _In_opt_ PWEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST pMakeCredentialRequest + ); + +#define WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST_VERSION_1 1 +#define WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST_CURRENT_VERSION WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST_VERSION_1 +typedef struct _WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST { + //Version of this structure, to allow for modifications in the future. + DWORD dwVersion; + + //RP ID. After UTF8 to Unicode conversion, + PCWSTR pwszRpId; + + //Input RP ID. Raw UTF8 bytes before conversion. + //These are the bytes to be hashed in the Authenticator Data. + DWORD cbRpId; + PBYTE pbRpId; + + //Client Data Hash + DWORD cbClientDataHash; + PBYTE pbClientDataHash; + + //Credentials used for inclusion + WEBAUTHN_CREDENTIAL_LIST CredentialList; + + //Optional extensions to parse when performing the operation. + DWORD cbCborExtensionsMap; + PBYTE pbCborExtensionsMap; + + // Authenticator Options (Optional) + PWEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS pAuthenticatorOptions; + + // Pin Auth (Optional) + BOOL fEmptyPinAuth; // Zero length PinAuth is included in the request + DWORD cbPinAuth; + PBYTE pbPinAuth; + + // HMAC Salt Extension (Optional) + PWEBAUTHN_CTAPCBOR_HMAC_SALT_EXTENSION pHmacSaltExtension; + + // PRF Extension + DWORD cbHmacSecretSaltValues; + PBYTE pbHmacSecretSaltValues; + + DWORD dwPinProtocol; + + //"credBlob": true extension + LONG lCredBlobExt; + + //"largeBlobKey": true extension + LONG lLargeBlobKeyExt; + + //"largeBlob" extension + DWORD dwCredLargeBlobOperation; + DWORD cbCredLargeBlobCompressed; + PBYTE pbCredLargeBlobCompressed; + DWORD dwCredLargeBlobOriginalSize; + + // "json" extension. Nonzero if present + DWORD cbJsonExt; + PBYTE pbJsonExt; +} WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST, *PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST; +typedef const WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST *PCWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST; + +_Success_(return == S_OK) +HRESULT +WINAPI +WebAuthNDecodeGetAssertionRequest( + _In_ DWORD cbEncoded, + _In_reads_bytes_(cbEncoded) const BYTE* pbEncoded, + _Outptr_ PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST* ppGetAssertionRequest + ); + +void +WINAPI +WebAuthNFreeDecodedGetAssertionRequest( + _In_opt_ PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST pGetAssertionRequest + ); + +typedef struct _WEBAUTHN_CTAPCBOR_GET_ASSERTION_RESPONSE { + // [1] credential (optional) + // [2] authenticatorData + // [3] signature + WEBAUTHN_ASSERTION WebAuthNAssertion; + + // [4] user (optional) + PCWEBAUTHN_USER_ENTITY_INFORMATION pUserInformation; + + // [5] numberOfCredentials (optional) + DWORD dwNumberOfCredentials; + + // [6] userSelected (optional) + LONG lUserSelected; + + // [7] largeBlobKey (optional) + DWORD cbLargeBlobKey; + PBYTE pbLargeBlobKey; + + // [8] unsignedExtensionOutputs + DWORD cbUnsignedExtensionOutputs; + PBYTE pbUnsignedExtensionOutputs; +} WEBAUTHN_CTAPCBOR_GET_ASSERTION_RESPONSE, *PWEBAUTHN_CTAPCBOR_GET_ASSERTION_RESPONSE; +typedef const WEBAUTHN_CTAPCBOR_GET_ASSERTION_RESPONSE *PCWEBAUTHN_CTAPCBOR_GET_ASSERTION_RESPONSE; + +_Success_(return == S_OK) +HRESULT +WINAPI +WebAuthNEncodeGetAssertionResponse( + _In_ PCWEBAUTHN_CTAPCBOR_GET_ASSERTION_RESPONSE pGetAssertionResponse, + _Out_ DWORD* pcbResp, + _Outptr_result_buffer_maybenull_(*pcbResp) BYTE** ppbResp + ); + +typedef void (CALLBACK* WEBAUTHN_PLUGIN_STATUS_CHANGE_CALLBACK )(void* context); + +HRESULT +WINAPI +WebAuthNPluginRegisterStatusChangeCallback( + _In_ WEBAUTHN_PLUGIN_STATUS_CHANGE_CALLBACK callback, + _In_ void* context, + _In_ REFCLSID rclsid, + _Out_ DWORD* pdwRegister + ); + +HRESULT +WINAPI +WebAuthNPluginUnregisterStatusChangeCallback( + _In_ DWORD* pdwRegister + ); + + +#ifdef __cplusplus +} // Balance extern "C" above +#endif + +#endif // WINAPI_FAMILY_PARTITION +#pragma endregion + + diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/assert.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/assert.rs new file mode 100644 index 00000000000..142fd129f5d --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/assert.rs @@ -0,0 +1,424 @@ +use serde_json; +use std::{ + alloc::{alloc, Layout}, + ptr, + sync::Arc, + time::Duration, +}; +use windows_core::{s, HRESULT}; + +use crate::ipc2::{ + PasskeyAssertionRequest, PasskeyAssertionResponse, Position, TimedCallback, UserVerification, + WindowsProviderClient, +}; +use crate::util::{debug_log, delay_load, wstr_to_string}; +use crate::webauthn::WEBAUTHN_CREDENTIAL_LIST; +use crate::{ + com_provider::{ + parse_credential_list, WebAuthnPluginOperationRequest, WebAuthnPluginOperationResponse, + }, + ipc2::PasskeyAssertionWithoutUserInterfaceRequest, +}; + +// Windows API types for WebAuthn (from webauthn.h.sample) +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST { + pub dwVersion: u32, + pub pwszRpId: *const u16, // PCWSTR + pub cbRpId: u32, + pub pbRpId: *const u8, + pub cbClientDataHash: u32, + pub pbClientDataHash: *const u8, + pub CredentialList: WEBAUTHN_CREDENTIAL_LIST, + pub cbCborExtensionsMap: u32, + pub pbCborExtensionsMap: *const u8, + pub pAuthenticatorOptions: *const crate::webauthn::WebAuthnCtapCborAuthenticatorOptions, + // Add other fields as needed... +} + +pub type PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST = *mut WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST; + +// Windows API function signatures for decoding get assertion requests +type WebAuthNDecodeGetAssertionRequestFn = unsafe extern "stdcall" fn( + cbEncoded: u32, + pbEncoded: *const u8, + ppGetAssertionRequest: *mut PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST, +) -> HRESULT; + +type WebAuthNFreeDecodedGetAssertionRequestFn = + unsafe extern "stdcall" fn(pGetAssertionRequest: PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST); + +// RAII wrapper for decoded get assertion request +pub struct DecodedGetAssertionRequest { + ptr: PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST, + free_fn: Option, +} + +impl DecodedGetAssertionRequest { + fn new( + ptr: PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST, + free_fn: Option, + ) -> Self { + Self { ptr, free_fn } + } + + pub fn as_ref(&self) -> &WEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST { + unsafe { &*self.ptr } + } +} + +impl Drop for DecodedGetAssertionRequest { + fn drop(&mut self) { + if !self.ptr.is_null() { + if let Some(free_fn) = self.free_fn { + tracing::debug!("Freeing decoded get assertion request"); + unsafe { + free_fn(self.ptr); + } + } + } + } +} + +// Function to decode get assertion request using Windows API +unsafe fn decode_get_assertion_request( + encoded_request: &[u8], +) -> Result { + tracing::debug!("Attempting to decode get assertion request using Windows API"); + + // Load the Windows WebAuthn API function + let decode_fn: Option = + delay_load(s!("webauthn.dll"), s!("WebAuthNDecodeGetAssertionRequest")); + + let decode_fn = + decode_fn.ok_or("Failed to load WebAuthNDecodeGetAssertionRequest from webauthn.dll")?; + + // Load the free function + let free_fn: Option = delay_load( + s!("webauthn.dll"), + s!("WebAuthNFreeDecodedGetAssertionRequest"), + ); + + let mut pp_get_assertion_request: PWEBAUTHN_CTAPCBOR_GET_ASSERTION_REQUEST = ptr::null_mut(); + + let result = decode_fn( + encoded_request.len() as u32, + encoded_request.as_ptr(), + &mut pp_get_assertion_request, + ); + + if result.is_err() || pp_get_assertion_request.is_null() { + return Err(format!( + "WebAuthNDecodeGetAssertionRequest failed with HRESULT: {}", + result.0 + )); + } + + Ok(DecodedGetAssertionRequest::new( + pp_get_assertion_request, + free_fn, + )) +} + +/// Helper for assertion requests +fn send_assertion_request( + ipc_client: &WindowsProviderClient, + request: PasskeyAssertionRequest, +) -> Result { + tracing::debug!( + "Assertion request data - RP ID: {}, Client data hash: {} bytes, Allowed credentials: {:?}", + request.rp_id, + request.client_data_hash.len(), + request.allowed_credentials, + ); + + let request_json = serde_json::to_string(&request) + .map_err(|err| format!("Failed to serialize assertion request: {err}"))?; + tracing::debug!(?request_json, "Sending assertion request"); + let callback = Arc::new(TimedCallback::new()); + if request.allowed_credentials.len() == 1 { + // copying this into another struct because I'm too lazy to make an enum right now. + let request = PasskeyAssertionWithoutUserInterfaceRequest { + rp_id: request.rp_id, + credential_id: request.allowed_credentials[0].clone(), + // user_name: request.user_name, + // user_handle: request., + // record_identifier: todo!(), + client_data_hash: request.client_data_hash, + user_verification: request.user_verification, + window_xy: request.window_xy, + }; + ipc_client.prepare_passkey_assertion_without_user_interface(request, callback.clone()); + } else { + ipc_client.prepare_passkey_assertion(request, callback.clone()); + } + callback + .wait_for_response(Duration::from_secs(30)) + .map_err(|_| "Registration request timed out".to_string())? + .map_err(|err| err.to_string()) +} + +/// Creates a WebAuthn get assertion response from Bitwarden's assertion response +unsafe fn create_get_assertion_response( + credential_id: Vec, + authenticator_data: Vec, + signature: Vec, + user_handle: Vec, +) -> std::result::Result<*mut WebAuthnPluginOperationResponse, HRESULT> { + // Construct a CTAP2 response with the proper structure + + // Create CTAP2 GetAssertion response map according to CTAP2 specification + let mut cbor_response: Vec<(ciborium::Value, ciborium::Value)> = Vec::new(); + + // [1] credential (optional) - Always include credential descriptor + let credential_map = vec![ + ( + ciborium::Value::Text("id".to_string()), + ciborium::Value::Bytes(credential_id.clone()), + ), + ( + ciborium::Value::Text("type".to_string()), + ciborium::Value::Text("public-key".to_string()), + ), + ]; + cbor_response.push(( + ciborium::Value::Integer(1.into()), + ciborium::Value::Map(credential_map), + )); + + // [2] authenticatorData (required) + cbor_response.push(( + ciborium::Value::Integer(2.into()), + ciborium::Value::Bytes(authenticator_data), + )); + + // [3] signature (required) + cbor_response.push(( + ciborium::Value::Integer(3.into()), + ciborium::Value::Bytes(signature), + )); + + // [4] user (optional) - include if user handle is provided + if !user_handle.is_empty() { + let user_map = vec![( + ciborium::Value::Text("id".to_string()), + ciborium::Value::Bytes(user_handle), + )]; + cbor_response.push(( + ciborium::Value::Integer(4.into()), + ciborium::Value::Map(user_map), + )); + } + + // [5] numberOfCredentials (optional) + cbor_response.push(( + ciborium::Value::Integer(5.into()), + ciborium::Value::Integer(1.into()), + )); + + let cbor_value = ciborium::Value::Map(cbor_response); + + // Encode to CBOR with error handling + let mut cbor_data = Vec::new(); + if let Err(e) = ciborium::ser::into_writer(&cbor_value, &mut cbor_data) { + debug_log(&format!( + "ERROR: Failed to encode CBOR assertion response: {:?}", + e + )); + return Err(HRESULT(-1)); + } + + debug_log(&format!( + "Formatted CBOR assertion response: {:?}", + cbor_data + )); + + let response_len = cbor_data.len(); + + // Allocate memory for the response data + let layout = Layout::from_size_align(response_len, 1).map_err(|_| HRESULT(-1))?; + let response_ptr = alloc(layout); + if response_ptr.is_null() { + return Err(HRESULT(-1)); + } + + // Copy response data + ptr::copy_nonoverlapping(cbor_data.as_ptr(), response_ptr, response_len); + + // Allocate memory for the response structure + let response_layout = Layout::new::(); + let operation_response_ptr = alloc(response_layout) as *mut WebAuthnPluginOperationResponse; + if operation_response_ptr.is_null() { + return Err(HRESULT(-1)); + } + + // Initialize the response + ptr::write( + operation_response_ptr, + WebAuthnPluginOperationResponse { + encoded_response_byte_count: response_len as u32, + encoded_response_pointer: response_ptr, + }, + ); + + Ok(operation_response_ptr) +} + +/// Implementation of PluginGetAssertion moved from com_provider.rs +pub unsafe fn plugin_get_assertion( + ipc_client: &WindowsProviderClient, + request: *const WebAuthnPluginOperationRequest, + response: *mut WebAuthnPluginOperationResponse, +) -> Result<(), HRESULT> { + tracing::debug!("PluginGetAssertion() called"); + + // Validate input parameters + if request.is_null() || response.is_null() { + tracing::debug!("Invalid parameters passed to PluginGetAssertion"); + return Err(HRESULT(-1)); + } + + let req = &*request; + let transaction_id = format!("{:?}", req.transaction_id); + let coords = req.window_coordinates().unwrap_or((400, 400)); + + debug_log(&format!( + "Get assertion request - Transaction: {}", + transaction_id + )); + + if req.encoded_request_byte_count == 0 || req.encoded_request_pointer.is_null() { + tracing::error!("No encoded request data provided"); + return Err(HRESULT(-1)); + } + + let encoded_request_slice = std::slice::from_raw_parts( + req.encoded_request_pointer, + req.encoded_request_byte_count as usize, + ); + + // Try to decode the request using Windows API + let decoded_wrapper = decode_get_assertion_request(encoded_request_slice).map_err(|err| { + tracing::debug!("Failed to decode get assertion request: {err}"); + HRESULT(-1) + })?; + let decoded_request = decoded_wrapper.as_ref(); + tracing::debug!("Successfully decoded get assertion request using Windows API"); + + // Extract RP information + let rpid = if decoded_request.pwszRpId.is_null() { + tracing::error!("RP ID is null"); + return Err(HRESULT(-1)); + } else { + match wstr_to_string(decoded_request.pwszRpId) { + Ok(id) => id, + Err(e) => { + tracing::error!("Failed to decode RP ID: {}", e); + return Err(HRESULT(-1)); + } + } + }; + + // Extract client data hash + let client_data_hash = + if decoded_request.cbClientDataHash == 0 || decoded_request.pbClientDataHash.is_null() { + tracing::error!("Client data hash is required for assertion"); + return Err(HRESULT(-1)); + } else { + let hash_slice = std::slice::from_raw_parts( + decoded_request.pbClientDataHash, + decoded_request.cbClientDataHash as usize, + ); + hash_slice.to_vec() + }; + + // Extract user verification requirement from authenticator options + let user_verification = if !decoded_request.pAuthenticatorOptions.is_null() { + let auth_options = &*decoded_request.pAuthenticatorOptions; + match auth_options.user_verification { + 1 => UserVerification::Required, + -1 => UserVerification::Discouraged, + 0 | _ => UserVerification::Preferred, // Default or undefined + } + } else { + UserVerification::Preferred // Default or undefined + }; + + // Extract allowed credentials from credential list + let allowed_credentials = parse_credential_list(&decoded_request.CredentialList); + + // Create Windows assertion request + let assertion_request = PasskeyAssertionRequest { + rp_id: rpid.clone(), + client_data_hash, + allowed_credentials: allowed_credentials.clone(), + window_xy: Position { + x: coords.0, + y: coords.1, + }, + user_verification, + }; + + tracing::debug!( + "Get assertion request - RP: {}, Allowed credentials: {:?}", + rpid, + allowed_credentials + ); + + // Send assertion request + let passkey_response = + send_assertion_request(ipc_client, assertion_request).map_err(|err| { + tracing::error!("Assertion request failed: {err}"); + HRESULT(-1) + })?; + tracing::debug!("Assertion response received: {:?}", passkey_response); + + // Create proper WebAuthn response from passkey_response + tracing::debug!("Creating WebAuthn get assertion response"); + + let webauthn_response = create_get_assertion_response( + passkey_response.credential_id, + passkey_response.authenticator_data, + passkey_response.signature, + passkey_response.user_handle, + ) + .map_err(|err| { + tracing::error!("Failed to create WebAuthn assertion response: {err}"); + HRESULT(-1) + })?; + tracing::debug!("Successfully created WebAuthn assertion response"); + (*response).encoded_response_byte_count = (*webauthn_response).encoded_response_byte_count; + (*response).encoded_response_pointer = (*webauthn_response).encoded_response_pointer; + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::ptr::slice_from_raw_parts; + + use super::create_get_assertion_response; + + #[test] + fn test_create_native_assertion_response() { + let credential_id = vec![1, 2, 3, 4]; + let authenticator_data = vec![5, 6, 7, 8]; + let signature = vec![9, 10, 11, 12]; + let user_handle = vec![13, 14, 15, 16]; + let slice = unsafe { + let response = *create_get_assertion_response( + credential_id, + authenticator_data, + signature, + user_handle, + ) + .unwrap(); + &*slice_from_raw_parts( + response.encoded_response_pointer, + response.encoded_response_byte_count as usize, + ) + }; + // CTAP2_OK, Map(5 elements) + assert_eq!([0x00, 0xa5], slice[..2]); + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_buffer.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_buffer.rs new file mode 100644 index 00000000000..af34107a050 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_buffer.rs @@ -0,0 +1,84 @@ +use std::alloc; +use std::mem::{align_of, MaybeUninit}; +use std::ptr::NonNull; +use windows::Win32::System::Com::CoTaskMemAlloc; + +#[repr(transparent)] +pub struct ComBuffer(NonNull>); + +impl ComBuffer { + /// Returns an COM-allocated buffer of `size`. + fn alloc(size: usize, for_slice: bool) -> Self { + #[expect(clippy::as_conversions)] + { + assert!(size <= isize::MAX as usize, "requested bad object size"); + } + + // SAFETY: Any size is valid to pass to Windows, even `0`. + let ptr = NonNull::new(unsafe { CoTaskMemAlloc(size) }).unwrap_or_else(|| { + // XXX: This doesn't have to be correct, just close enough for an OK OOM error. + let layout = alloc::Layout::from_size_align(size, align_of::()).unwrap(); + alloc::handle_alloc_error(layout) + }); + + if for_slice { + // Ininitialize the buffer so it can later be treated as `&mut [u8]`. + // SAFETY: The pointer is valid and we are using a valid value for a byte-wise allocation. + unsafe { ptr.write_bytes(0, size) }; + } + + Self(ptr.cast()) + } + + fn into_ptr(self) -> *mut T { + self.0.cast().as_ptr() + } + + /// Creates a new COM-allocated structure. + /// + /// Note that `T` must be [Copy] to avoid any possible memory leaks. + pub fn with_object(object: T) -> *mut T { + // NB: Vendored from Rust's alloc code since we can't yet allocate `Box` with a custom allocator. + const MIN_ALIGN: usize = if cfg!(target_pointer_width = "64") { + 16 + } else if cfg!(target_pointer_width = "32") { + 8 + } else { + panic!("unsupported arch") + }; + + // SAFETY: Validate that our alignment works for a normal size-based allocation for soundness. + let layout = const { + let layout = alloc::Layout::new::(); + assert!(layout.align() <= MIN_ALIGN); + layout + }; + + let buffer = Self::alloc(layout.size(), false); + // SAFETY: `ptr` is valid for writes of `T` because we correctly allocated the right sized buffer that + // accounts for any alignment requirements. + // + // Additionally, we ensure the value is treated as moved by forgetting the source. + unsafe { buffer.0.cast::().write(object) }; + buffer.into_ptr() + } + + pub fn from_buffer>(buffer: T) -> (*mut u8, u32) { + let buffer = buffer.as_ref(); + let len = buffer.len(); + let com_buffer = Self::alloc(len, true); + + // SAFETY: `ptr` points to a valid allocation that `len` matches, and we made sure + // the bytes were initialized. Additionally, bytes have no alignment requirements. + unsafe { + NonNull::slice_from_raw_parts(com_buffer.0.cast::(), len) + .as_mut() + .copy_from_slice(buffer) + } + + // Safety: The Windows API structures these buffers are placed into use `u32` (`DWORD`) to + // represent length. + #[expect(clippy::as_conversions)] + (com_buffer.into_ptr(), len as u32) + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_provider.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_provider.rs new file mode 100644 index 00000000000..fe9de79e483 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_provider.rs @@ -0,0 +1,229 @@ +use windows::Win32::Foundation::{RECT, S_OK}; +use windows::Win32::System::Com::*; +use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; +use windows_core::{implement, interface, IInspectable, IUnknown, Interface, HRESULT}; + +use crate::assert::plugin_get_assertion; +use crate::ipc2::WindowsProviderClient; +use crate::make_credential::plugin_make_credential; +use crate::util::debug_log; +use crate::webauthn::WEBAUTHN_CREDENTIAL_LIST; + +/// Plugin request type enum as defined in the IDL +#[repr(u32)] +#[derive(Debug, Copy, Clone)] +pub enum WebAuthnPluginRequestType { + CTAP2_CBOR = 0x01, +} + +/// Plugin lock status enum as defined in the IDL +#[repr(u32)] +#[derive(Debug, Copy, Clone)] +pub enum PluginLockStatus { + PluginLocked = 0, + PluginUnlocked = 1, +} + +/// Used when creating and asserting credentials. +/// Header File Name: _WEBAUTHN_PLUGIN_OPERATION_REQUEST +/// Header File Usage: MakeCredential() +/// GetAssertion() +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WebAuthnPluginOperationRequest { + pub window_handle: windows::Win32::Foundation::HWND, + pub transaction_id: windows_core::GUID, + pub request_signature_byte_count: u32, + pub request_signature_pointer: *mut u8, + pub request_type: WebAuthnPluginRequestType, + pub encoded_request_byte_count: u32, + pub encoded_request_pointer: *mut u8, +} + +impl WebAuthnPluginOperationRequest { + pub fn window_coordinates(&self) -> Result<(i32, i32), windows::core::Error> { + let mut window: RECT = RECT::default(); + unsafe { + GetWindowRect(self.window_handle, &mut window)?; + } + // TODO: This isn't quite right, but it's closer than what we had + let center_x = (window.right + window.left) / 2; + let center_y = (window.bottom + window.top) / 2; + Ok((center_x, center_y)) + } +} +/// Used as a response when creating and asserting credentials. +/// Header File Name: _WEBAUTHN_PLUGIN_OPERATION_RESPONSE +/// Header File Usage: MakeCredential() +/// GetAssertion() +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WebAuthnPluginOperationResponse { + pub encoded_response_byte_count: u32, + pub encoded_response_pointer: *mut u8, +} + +/// Used to cancel an operation. +/// Header File Name: _WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST +/// Header File Usage: CancelOperation() +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WebAuthnPluginCancelOperationRequest { + pub transaction_id: windows_core::GUID, + pub request_signature_byte_count: u32, + pub request_signature_pointer: *mut u8, +} + +// Stable IPluginAuthenticator interface +#[interface("d26bcf6f-b54c-43ff-9f06-d5bf148625f7")] +pub unsafe trait IPluginAuthenticator: windows_core::IUnknown { + fn MakeCredential( + &self, + request: *const WebAuthnPluginOperationRequest, + response: *mut WebAuthnPluginOperationResponse, + ) -> HRESULT; + fn GetAssertion( + &self, + request: *const WebAuthnPluginOperationRequest, + response: *mut WebAuthnPluginOperationResponse, + ) -> HRESULT; + fn CancelOperation(&self, request: *const WebAuthnPluginCancelOperationRequest) -> HRESULT; + fn GetLockStatus(&self, lock_status: *mut PluginLockStatus) -> HRESULT; +} + +pub unsafe fn parse_credential_list(credential_list: &WEBAUTHN_CREDENTIAL_LIST) -> Vec> { + let mut allowed_credentials = Vec::new(); + + if credential_list.cCredentials == 0 || credential_list.ppCredentials.is_null() { + tracing::debug!("No credentials in credential list"); + return allowed_credentials; + } + + debug_log(&format!( + "Parsing {} credentials from credential list", + credential_list.cCredentials + )); + + // ppCredentials is an array of pointers to WEBAUTHN_CREDENTIAL_EX + let credentials_array = std::slice::from_raw_parts( + credential_list.ppCredentials, + credential_list.cCredentials as usize, + ); + + for (i, &credential_ptr) in credentials_array.iter().enumerate() { + if credential_ptr.is_null() { + tracing::debug!("WARNING: Credential {} is null, skipping", i); + continue; + } + + let credential = &*credential_ptr; + + if credential.cbId == 0 || credential.pbId.is_null() { + debug_log(&format!( + "WARNING: Credential {} has invalid ID, skipping", + i + )); + continue; + } + // Extract credential ID bytes + // For some reason, we're getting hex strings from Windows instead of bytes. + let credential_id_slice = + std::slice::from_raw_parts(credential.pbId, credential.cbId as usize); + + debug_log(&format!( + "Parsed credential {}: {} bytes, {:?}", + i, credential.cbId, &credential_id_slice, + )); + allowed_credentials.push(credential_id_slice.to_vec()); + } + + debug_log(&format!( + "Successfully parsed {} allowed credentials", + allowed_credentials.len() + )); + allowed_credentials +} + +#[implement(IPluginAuthenticator)] +pub struct PluginAuthenticatorComObject { + client: WindowsProviderClient, +} + +#[implement(IClassFactory)] +pub struct Factory; + +impl IPluginAuthenticator_Impl for PluginAuthenticatorComObject_Impl { + unsafe fn MakeCredential( + &self, + request: *const WebAuthnPluginOperationRequest, + response: *mut WebAuthnPluginOperationResponse, + ) -> HRESULT { + tracing::debug!("MakeCredential() called"); + tracing::debug!("version2"); + // Convert to legacy format for internal processing + if request.is_null() || response.is_null() { + tracing::debug!("MakeCredential: Invalid request or response pointers passed"); + return HRESULT(-1); + } + + let response = match plugin_make_credential(&self.client, request, response) { + Ok(()) => S_OK, + Err(err) => err, + }; + tracing::debug!("MakeCredential() completed"); + response + } + + unsafe fn GetAssertion( + &self, + request: *const WebAuthnPluginOperationRequest, + response: *mut WebAuthnPluginOperationResponse, + ) -> HRESULT { + tracing::debug!("GetAssertion() called"); + if request.is_null() || response.is_null() { + return HRESULT(-1); + } + + match plugin_get_assertion(&self.client, request, response) { + Ok(()) => S_OK, + Err(err) => err, + } + } + + unsafe fn CancelOperation( + &self, + _request: *const WebAuthnPluginCancelOperationRequest, + ) -> HRESULT { + tracing::debug!("CancelOperation() called"); + HRESULT(0) + } + + unsafe fn GetLockStatus(&self, lock_status: *mut PluginLockStatus) -> HRESULT { + tracing::debug!("GetLockStatus() called"); + if lock_status.is_null() { + return HRESULT(-2147024809); // E_INVALIDARG + } + *lock_status = PluginLockStatus::PluginUnlocked; + HRESULT(0) + } +} + +impl IClassFactory_Impl for Factory_Impl { + fn CreateInstance( + &self, + _outer: windows_core::Ref, + iid: *const windows_core::GUID, + object: *mut *mut core::ffi::c_void, + ) -> windows_core::Result<()> { + tracing::debug!("Creating COM server instance."); + tracing::debug!("Trying to connect to Bitwarden IPC"); + let client = WindowsProviderClient::connect(); + tracing::debug!("Connected to Bitwarden IPC"); + let unknown: IInspectable = PluginAuthenticatorComObject { client }.into(); // TODO: IUnknown ? + unsafe { unknown.query(iid, object).ok() } + } + + fn LockServer(&self, _lock: windows_core::BOOL) -> windows_core::Result<()> { + Ok(()) + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_registration.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_registration.rs new file mode 100644 index 00000000000..f39cd3798c3 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/com_registration.rs @@ -0,0 +1,338 @@ +use std::ptr; + +use base64::{engine::general_purpose::STANDARD, Engine as _}; +use windows::Win32::System::Com::*; +use windows_core::{s, ComObjectInterface, GUID, HRESULT, HSTRING, PCWSTR}; + +use crate::com_provider; +use crate::util::delay_load; +use crate::webauthn::*; +use ciborium::value::Value; + +const AUTHENTICATOR_NAME: &str = "Bitwarden Desktop"; +const CLSID: &str = "0f7dc5d9-69ce-4652-8572-6877fd695062"; +const RPID: &str = "bitwarden.com"; +const AAGUID: &str = "d548826e-79b4-db40-a3d8-11116f7e8349"; +const LOGO_SVG: &str = r##""##; + +/// Parses a UUID string (with hyphens) into bytes +fn parse_uuid_to_bytes(uuid_str: &str) -> Result, String> { + let uuid_clean = uuid_str.replace("-", ""); + if uuid_clean.len() != 32 { + return Err("Invalid UUID format".to_string()); + } + + uuid_clean + .chars() + .collect::>() + .chunks(2) + .map(|chunk| { + let hex_str: String = chunk.iter().collect(); + u8::from_str_radix(&hex_str, 16) + .map_err(|_| format!("Invalid hex character in UUID: {}", hex_str)) + }) + .collect() +} + +/// Converts a CLSID string to a GUID +pub(crate) fn parse_clsid_to_guid_str(clsid_str: &str) -> Result { + // Remove hyphens and parse as hex + let clsid_clean = clsid_str.replace("-", ""); + if clsid_clean.len() != 32 { + return Err("Invalid CLSID format".to_string()); + } + + // Convert to u128 and create GUID + let clsid_u128 = u128::from_str_radix(&clsid_clean, 16) + .map_err(|_| "Failed to parse CLSID as hex".to_string())?; + + Ok(GUID::from_u128(clsid_u128)) +} + +/// Converts the CLSID constant string to a GUID +fn parse_clsid_to_guid() -> Result { + parse_clsid_to_guid_str(CLSID) +} + +/// Generates CBOR-encoded authenticator info according to FIDO CTAP2 specifications +/// See: https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#authenticatorGetInfo +fn generate_cbor_authenticator_info() -> Result, String> { + // Parse AAGUID from string format to bytes + let aaguid_bytes = parse_uuid_to_bytes(AAGUID)?; + + // Create the authenticator info map according to CTAP2 spec + // Using Vec<(Value, Value)> because that's what ciborium::Value::Map expects + let mut authenticator_info = Vec::new(); + + // 1: versions - Array of supported FIDO versions + authenticator_info.push(( + Value::Integer(1.into()), + Value::Array(vec![ + Value::Text("FIDO_2_0".to_string()), + Value::Text("FIDO_2_1".to_string()), + ]), + )); + + // 2: extensions - Array of supported extensions (empty for now) + authenticator_info.push((Value::Integer(2.into()), Value::Array(vec![]))); + + // 3: aaguid - 16-byte AAGUID + authenticator_info.push((Value::Integer(3.into()), Value::Bytes(aaguid_bytes))); + + // 4: options - Map of supported options + let options = vec![ + (Value::Text("rk".to_string()), Value::Bool(true)), // resident key + (Value::Text("up".to_string()), Value::Bool(true)), // user presence + (Value::Text("uv".to_string()), Value::Bool(true)), // user verification + ]; + authenticator_info.push((Value::Integer(4.into()), Value::Map(options))); + + // 9: transports - Array of supported transports + authenticator_info.push(( + Value::Integer(9.into()), + Value::Array(vec![ + Value::Text("internal".to_string()), + Value::Text("hybrid".to_string()), + ]), + )); + + // 10: algorithms - Array of supported algorithms + let algorithm = vec![ + (Value::Text("alg".to_string()), Value::Integer((-7).into())), // ES256 + ( + Value::Text("type".to_string()), + Value::Text("public-key".to_string()), + ), + ]; + authenticator_info.push(( + Value::Integer(10.into()), + Value::Array(vec![Value::Map(algorithm)]), + )); + + // Encode to CBOR + let mut buffer = Vec::new(); + ciborium::ser::into_writer(&Value::Map(authenticator_info), &mut buffer) + .map_err(|e| format!("Failed to encode CBOR: {}", e))?; + + Ok(buffer) +} + +/// Initializes the COM library for use on the calling thread, +/// and registers + sets the security values. +pub fn initialize_com_library() -> std::result::Result<(), String> { + let result = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + + if result.is_err() { + return Err(format!( + "Error: couldn't initialize the COM library\n{}", + result.message() + )); + } + + match unsafe { + CoInitializeSecurity( + None, + -1, + None, + None, + RPC_C_AUTHN_LEVEL_DEFAULT, + RPC_C_IMP_LEVEL_IMPERSONATE, + None, + EOAC_NONE, + None, + ) + } { + Ok(_) => Ok(()), + Err(e) => Err(format!( + "Error: couldn't initialize COM security\n{}", + e.message() + )), + } +} + +/// Registers the Bitwarden Plugin Authenticator COM library with Windows. +pub fn register_com_library() -> std::result::Result<(), String> { + static FACTORY: windows_core::StaticComObject = + com_provider::Factory.into_static(); + let clsid_guid = parse_clsid_to_guid().map_err(|e| format!("Failed to parse CLSID: {}", e))?; + let clsid: *const GUID = &clsid_guid; + + match unsafe { + CoRegisterClassObject( + clsid, + FACTORY.as_interface_ref(), + //FACTORY.as_interface::(), + CLSCTX_LOCAL_SERVER, + REGCLS_MULTIPLEUSE, + ) + } { + Ok(_) => Ok(()), + Err(e) => Err(format!( + "Error: couldn't register the COM library\n{}", + e.message() + )), + } +} + +/// Adds Bitwarden as a plugin authenticator. +pub fn add_authenticator() -> std::result::Result<(), String> { + let authenticator_name: HSTRING = AUTHENTICATOR_NAME.into(); + let authenticator_name_ptr = PCWSTR(authenticator_name.as_ptr()).as_ptr(); + + // Parse CLSID into GUID structure + let clsid_guid = + parse_clsid_to_guid().map_err(|e| format!("Failed to parse CLSID to GUID: {}", e))?; + + let relying_party_id: HSTRING = RPID.into(); + let relying_party_id_ptr = PCWSTR(relying_party_id.as_ptr()).as_ptr(); + + // Base64-encode the SVG as required by Windows API + let logo_b64: String = STANDARD.encode(LOGO_SVG); + let logo_b64_buf: Vec = logo_b64.encode_utf16().chain(std::iter::once(0)).collect(); + + // Generate CBOR authenticator info dynamically + let authenticator_info_bytes = generate_cbor_authenticator_info() + .map_err(|e| format!("Failed to generate authenticator info: {}", e))?; + + let add_authenticator_options = WebAuthnPluginAddAuthenticatorOptions { + authenticator_name: authenticator_name_ptr, + rclsid: &clsid_guid, // Changed to GUID reference + rpid: relying_party_id_ptr, + light_theme_logo_svg: logo_b64_buf.as_ptr(), + dark_theme_logo_svg: logo_b64_buf.as_ptr(), + cbor_authenticator_info_byte_count: authenticator_info_bytes.len() as u32, + cbor_authenticator_info: authenticator_info_bytes.as_ptr(), // Use as_ptr() not as_mut_ptr() + supported_rp_ids_count: 0, // NEW field: 0 means all RPs supported + supported_rp_ids: ptr::null(), // NEW field + }; + + let mut add_response_ptr: *mut WebAuthnPluginAddAuthenticatorResponse = ptr::null_mut(); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAddAuthenticator"), // Stable function name + ) + }; + + match result { + Some(api) => { + let result = unsafe { api(&add_authenticator_options, &mut add_response_ptr) }; + + if result.is_err() { + return Err(format!( + "Error: Error response from WebAuthNPluginAddAuthenticator()\n{}", + result.message() + )); + } + + // Free the response if needed + if !add_response_ptr.is_null() { + free_add_authenticator_response(add_response_ptr); + } + + Ok(()) + }, + None => { + Err(String::from("Error: Can't complete add_authenticator(), as the function WebAuthNPluginAddAuthenticator can't be found.")) + } + } +} + +fn free_add_authenticator_response(response: *mut WebAuthnPluginAddAuthenticatorResponse) { + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginFreeAddAuthenticatorResponse"), + ) + }; + + if let Some(api) = result { + unsafe { api(response) }; + } +} + +type WebAuthNPluginAddAuthenticatorFnDeclaration = unsafe extern "cdecl" fn( + pPluginAddAuthenticatorOptions: *const WebAuthnPluginAddAuthenticatorOptions, + ppPluginAddAuthenticatorResponse: *mut *mut WebAuthnPluginAddAuthenticatorResponse, +) -> HRESULT; + +type WebAuthNPluginFreeAddAuthenticatorResponseFnDeclaration = unsafe extern "cdecl" fn( + pPluginAddAuthenticatorResponse: *mut WebAuthnPluginAddAuthenticatorResponse, +); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_generate_cbor_authenticator_info() { + let result = generate_cbor_authenticator_info(); + assert!(result.is_ok(), "CBOR generation should succeed"); + + let cbor_bytes = result.unwrap(); + assert!(!cbor_bytes.is_empty(), "CBOR bytes should not be empty"); + + // Verify the CBOR can be decoded back + let decoded: Result = ciborium::de::from_reader(&cbor_bytes[..]); + assert!(decoded.is_ok(), "Generated CBOR should be valid"); + + // Verify it's a map with expected keys + if let Value::Map(map) = decoded.unwrap() { + assert!( + map.iter().any(|(k, _)| k == &Value::Integer(1.into())), + "Should contain versions (key 1)" + ); + assert!( + map.iter().any(|(k, _)| k == &Value::Integer(2.into())), + "Should contain extensions (key 2)" + ); + assert!( + map.iter().any(|(k, _)| k == &Value::Integer(3.into())), + "Should contain aaguid (key 3)" + ); + assert!( + map.iter().any(|(k, _)| k == &Value::Integer(4.into())), + "Should contain options (key 4)" + ); + assert!( + map.iter().any(|(k, _)| k == &Value::Integer(9.into())), + "Should contain transports (key 9)" + ); + assert!( + map.iter().any(|(k, _)| k == &Value::Integer(10.into())), + "Should contain algorithms (key 10)" + ); + } else { + panic!("CBOR should decode to a map"); + } + + // Print the generated CBOR for verification + println!("Generated CBOR hex: {}", hex::encode(&cbor_bytes)); + } + + #[test] + fn test_aaguid_parsing() { + let result = parse_uuid_to_bytes(AAGUID); + assert!(result.is_ok(), "AAGUID parsing should succeed"); + + let aaguid_bytes = result.unwrap(); + assert_eq!(aaguid_bytes.len(), 16, "AAGUID should be 16 bytes"); + assert_eq!(aaguid_bytes[0], 0xd5, "First byte should be 0xd5"); + assert_eq!(aaguid_bytes[1], 0x48, "Second byte should be 0x48"); + + // Verify full expected AAGUID + let expected_hex = "d548826e79b4db40a3d811116f7e8349"; + let expected_bytes = hex::decode(expected_hex).unwrap(); + assert_eq!( + aaguid_bytes, expected_bytes, + "AAGUID should match expected value" + ); + } + + #[test] + fn test_parse_clsid_to_guid() { + let result = parse_clsid_to_guid(); + assert!(result.is_ok(), "CLSID parsing should succeed"); + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/assertion.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/assertion.rs new file mode 100644 index 00000000000..367ee51bfc8 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/assertion.rs @@ -0,0 +1,57 @@ +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use super::{BitwardenError, Callback, Position, UserVerification}; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PasskeyAssertionRequest { + pub rp_id: String, + pub client_data_hash: Vec, + pub user_verification: UserVerification, + pub allowed_credentials: Vec>, + pub window_xy: Position, + // pub extension_input: Vec, TODO: Implement support for extensions +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PasskeyAssertionWithoutUserInterfaceRequest { + pub rp_id: String, + pub credential_id: Vec, + // pub user_name: String, + // pub user_handle: Vec, + // pub record_identifier: Option, + pub client_data_hash: Vec, + pub user_verification: UserVerification, + pub window_xy: Position, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PasskeyAssertionResponse { + pub rp_id: String, + pub user_handle: Vec, + pub signature: Vec, + pub client_data_hash: Vec, + pub authenticator_data: Vec, + pub credential_id: Vec, +} + +pub trait PreparePasskeyAssertionCallback: Send + Sync { + fn on_complete(&self, credential: PasskeyAssertionResponse); + fn on_error(&self, error: BitwardenError); +} + +impl Callback for Arc { + fn complete(&self, credential: serde_json::Value) -> Result<(), serde_json::Error> { + let credential = serde_json::from_value(credential)?; + PreparePasskeyAssertionCallback::on_complete(self.as_ref(), credential); + Ok(()) + } + + fn error(&self, error: BitwardenError) { + PreparePasskeyAssertionCallback::on_error(self.as_ref(), error); + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/mod.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/mod.rs new file mode 100644 index 00000000000..256c23c215b --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/mod.rs @@ -0,0 +1,369 @@ +use std::{ + collections::HashMap, + error::Error, + fmt::Display, + sync::{ + atomic::AtomicU32, + mpsc::{self, Receiver, Sender}, + Arc, Mutex, Once, + }, + time::{Duration, Instant}, +}; + +use futures::FutureExt; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use tracing::{error, info}; +use tracing_subscriber::{ + filter::{EnvFilter, LevelFilter}, + layer::SubscriberExt, + util::SubscriberInitExt, +}; + +mod assertion; +mod registration; + +pub use assertion::{ + PasskeyAssertionRequest, PasskeyAssertionResponse, PasskeyAssertionWithoutUserInterfaceRequest, + PreparePasskeyAssertionCallback, +}; +pub use registration::{ + PasskeyRegistrationRequest, PasskeyRegistrationResponse, PreparePasskeyRegistrationCallback, +}; + +use crate::util::debug_log; + +static INIT: Once = Once::new(); + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum UserVerification { + Preferred, + Required, + Discouraged, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Position { + pub x: i32, + pub y: i32, +} + +#[derive(Debug, Serialize, Deserialize)] +pub enum BitwardenError { + Internal(String), +} + +impl Display for BitwardenError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Internal(msg) => write!(f, "Internal error occurred: {msg}"), + } + } +} + +impl Error for BitwardenError {} + +// TODO: These have to be named differently than the actual Uniffi traits otherwise +// the generated code will lead to ambiguous trait implementations +// These are only used internally, so it doesn't matter that much +trait Callback: Send + Sync { + fn complete(&self, credential: serde_json::Value) -> Result<(), serde_json::Error>; + fn error(&self, error: BitwardenError); +} + +#[derive(Debug)] +/// Store the connection status between the Windows credential provider extension +/// and the desktop application's IPC server. +pub enum ConnectionStatus { + Connected, + Disconnected, +} + +pub struct WindowsProviderClient { + to_server_send: tokio::sync::mpsc::Sender, + + // We need to keep track of the callbacks so we can call them when we receive a response + response_callbacks_counter: AtomicU32, + #[allow(clippy::type_complexity)] + response_callbacks_queue: Arc, Instant)>>>, + + // Flag to track connection status - atomic for thread safety without locks + connection_status: Arc, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +/// Store native desktop status information to use for IPC communication +/// between the application and the Windows credential provider. +pub struct NativeStatus { + key: String, + value: String, +} + +// In our callback management, 0 is a reserved sequence number indicating that a message does not have a callback. +const NO_CALLBACK_INDICATOR: u32 = 0; + +impl WindowsProviderClient { + // FIXME: Remove unwraps! They panic and terminate the whole application. + #[allow(clippy::unwrap_used)] + pub fn connect() -> Self { + debug_log("YO!"); + INIT.call_once(|| { + /* + let filter = EnvFilter::builder() + .with_default_directive(LevelFilter::DEBUG.into()) + .from_env_lossy(); + + let log_file_path = "C:\\temp\\bitwarden_windows_passkey_provider.log"; + debug_log(&format!("Trying to set up log file at {log_file_path}")); + // FIXME: Remove unwrap + let file = std::fs::File::options() + .append(true) + .open(log_file_path) + .unwrap(); + let log_file = tracing_subscriber::fmt::layer().with_writer(file); + tracing_subscriber::registry() + .with(filter) + .with(log_file) + .init(); + */ + }); + tracing::debug!("Windows COM server trying to connect to Electron IPC..."); + + let (from_server_send, mut from_server_recv) = tokio::sync::mpsc::channel(32); + let (to_server_send, to_server_recv) = tokio::sync::mpsc::channel(32); + + let client = WindowsProviderClient { + to_server_send, + response_callbacks_counter: AtomicU32::new(1), // Start at 1 since 0 is reserved for "no callback" scenarios + response_callbacks_queue: Arc::new(Mutex::new(HashMap::new())), + connection_status: Arc::new(std::sync::atomic::AtomicBool::new(false)), + }; + + let path = desktop_core::ipc::path("af"); + + let queue = client.response_callbacks_queue.clone(); + let connection_status = client.connection_status.clone(); + + std::thread::spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("Can't create runtime"); + + rt.spawn( + desktop_core::ipc::client::connect(path, from_server_send, to_server_recv) + .map(|r| r.map_err(|e| e.to_string())), + ); + + rt.block_on(async move { + while let Some(message) = from_server_recv.recv().await { + match serde_json::from_str::(&message) { + Ok(SerializedMessage::Command(CommandMessage::Connected)) => { + info!("Connected to server"); + connection_status.store(true, std::sync::atomic::Ordering::Relaxed); + } + Ok(SerializedMessage::Command(CommandMessage::Disconnected)) => { + info!("Disconnected from server"); + connection_status.store(false, std::sync::atomic::Ordering::Relaxed); + } + Ok(SerializedMessage::Message { + sequence_number, + value, + }) => match queue.lock().unwrap().remove(&sequence_number) { + Some((cb, request_start_time)) => { + info!( + "Time to process request: {:?}", + request_start_time.elapsed() + ); + match value { + Ok(value) => { + if let Err(e) = cb.complete(value) { + error!(error = %e, "Error deserializing message"); + } + } + Err(e) => { + error!(error = ?e, "Error processing message"); + cb.error(e) + } + } + } + None => { + error!(sequence_number, "No callback found for sequence number") + } + }, + Err(e) => { + error!(error = %e, "Error deserializing message"); + } + }; + } + }); + }); + + client + } + + pub fn send_native_status(&self, key: String, value: String) { + let status = NativeStatus { key, value }; + self.send_message(status, None); + } + + pub fn prepare_passkey_registration( + &self, + request: PasskeyRegistrationRequest, + callback: Arc, + ) { + self.send_message(request, Some(Box::new(callback))); + } + + pub fn prepare_passkey_assertion( + &self, + request: PasskeyAssertionRequest, + callback: Arc, + ) { + self.send_message(request, Some(Box::new(callback))); + } + + pub fn prepare_passkey_assertion_without_user_interface( + &self, + request: PasskeyAssertionWithoutUserInterfaceRequest, + callback: Arc, + ) { + self.send_message(request, Some(Box::new(callback))); + } + + pub fn get_connection_status(&self) -> ConnectionStatus { + let is_connected = self + .connection_status + .load(std::sync::atomic::Ordering::Relaxed); + if is_connected { + ConnectionStatus::Connected + } else { + ConnectionStatus::Disconnected + } + } +} + +#[derive(Serialize, Deserialize)] +#[serde(tag = "command", rename_all = "camelCase")] +enum CommandMessage { + Connected, + Disconnected, +} + +#[derive(Serialize, Deserialize)] +#[serde(untagged, rename_all = "camelCase")] +enum SerializedMessage { + Command(CommandMessage), + Message { + sequence_number: u32, + value: Result, + }, +} + +impl WindowsProviderClient { + #[allow(clippy::unwrap_used)] + fn add_callback(&self, callback: Box) -> u32 { + let sequence_number = self + .response_callbacks_counter + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + + self.response_callbacks_queue + .lock() + .expect("response callbacks queue mutex should not be poisoned") + .insert(sequence_number, (callback, Instant::now())); + + sequence_number + } + + #[allow(clippy::unwrap_used)] + fn send_message( + &self, + message: impl Serialize + DeserializeOwned, + callback: Option>, + ) { + let sequence_number = if let Some(callback) = callback { + self.add_callback(callback) + } else { + NO_CALLBACK_INDICATOR + }; + + let message = serde_json::to_string(&SerializedMessage::Message { + sequence_number, + value: Ok(serde_json::to_value(message).unwrap()), + }) + .expect("Can't serialize message"); + + if let Err(e) = self.to_server_send.blocking_send(message) { + // Make sure we remove the callback from the queue if we can't send the message + if sequence_number != NO_CALLBACK_INDICATOR { + if let Some((callback, _)) = self + .response_callbacks_queue + .lock() + .expect("response callbacks queue mutex should not be poisoned") + .remove(&sequence_number) + { + callback.error(BitwardenError::Internal(format!( + "Error sending message: {e}" + ))); + } + } + } + } +} + +pub struct TimedCallback { + tx: Mutex>>>, + rx: Mutex>>, +} + +impl TimedCallback { + pub fn new() -> Self { + let (tx, rx) = mpsc::channel(); + Self { + tx: Mutex::new(Some(tx)), + rx: Mutex::new(rx), + } + } + + pub fn wait_for_response( + &self, + timeout: Duration, + ) -> Result, mpsc::RecvTimeoutError> { + self.rx.lock().unwrap().recv_timeout(timeout) + } + + fn send(&self, response: Result) { + match self.tx.lock().unwrap().take() { + Some(tx) => { + if let Err(_) = tx.send(response) { + tracing::error!("Windows provider channel closed before receiving IPC response from Electron") + } + } + None => { + tracing::error!("Callback channel used before response: multi-threading issue?"); + } + } + } +} + +impl PreparePasskeyRegistrationCallback for TimedCallback { + fn on_complete(&self, credential: PasskeyRegistrationResponse) { + self.send(Ok(credential)); + } + + fn on_error(&self, error: BitwardenError) { + self.send(Err(error)) + } +} + +impl PreparePasskeyAssertionCallback for TimedCallback { + fn on_complete(&self, credential: PasskeyAssertionResponse) { + self.send(Ok(credential)); + } + + fn on_error(&self, error: BitwardenError) { + self.send(Err(error)) + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/registration.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/registration.rs new file mode 100644 index 00000000000..3ac6808cb49 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/ipc2/registration.rs @@ -0,0 +1,44 @@ +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use super::{BitwardenError, Callback, Position, UserVerification}; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PasskeyRegistrationRequest { + pub rp_id: String, + pub user_name: String, + pub user_handle: Vec, + pub client_data_hash: Vec, + pub user_verification: UserVerification, + pub supported_algorithms: Vec, + pub window_xy: Position, + pub excluded_credentials: Vec>, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PasskeyRegistrationResponse { + pub rp_id: String, + pub client_data_hash: Vec, + pub credential_id: Vec, + pub attestation_object: Vec, +} + +pub trait PreparePasskeyRegistrationCallback: Send + Sync { + fn on_complete(&self, credential: PasskeyRegistrationResponse); + fn on_error(&self, error: BitwardenError); +} + +impl Callback for Arc { + fn complete(&self, credential: serde_json::Value) -> Result<(), serde_json::Error> { + let credential = serde_json::from_value(credential)?; + PreparePasskeyRegistrationCallback::on_complete(self.as_ref(), credential); + Ok(()) + } + + fn error(&self, error: BitwardenError) { + PreparePasskeyRegistrationCallback::on_error(self.as_ref(), error); + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/lib.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/lib.rs index 2e4f453d8f0..73c085ef83b 100644 --- a/apps/desktop/desktop_native/windows_plugin_authenticator/src/lib.rs +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/lib.rs @@ -2,175 +2,35 @@ #![allow(non_snake_case)] #![allow(non_camel_case_types)] -use std::ffi::c_uchar; -use std::ptr; -use windows::Win32::Foundation::*; -use windows::Win32::System::Com::*; -use windows::Win32::System::LibraryLoader::*; -use windows_core::*; - -mod pluginauthenticator; +// New modular structure +mod assert; +mod com_buffer; +mod com_provider; +mod com_registration; +mod ipc2; +mod make_credential; +mod types; +mod util; mod webauthn; -const AUTHENTICATOR_NAME: &str = "Bitwarden Desktop Authenticator"; -//const AAGUID: &str = "d548826e-79b4-db40-a3d8-11116f7e8349"; -const CLSID: &str = "0f7dc5d9-69ce-4652-8572-6877fd695062"; -const RPID: &str = "bitwarden.com"; +// Re-export main functionality +pub use com_registration::{add_authenticator, initialize_com_library, register_com_library}; +pub use types::UserVerificationRequirement; /// Handles initialization and registration for the Bitwarden desktop app as a -/// plugin authenticator with Windows. /// For now, also adds the authenticator pub fn register() -> std::result::Result<(), String> { - initialize_com_library()?; + // TODO: Can we spawn a new named thread for debugging? + tracing::debug!("register() called..."); - register_com_library()?; + let r = com_registration::initialize_com_library(); + tracing::debug!("Initialized the com library: {:?}", r); - add_authenticator()?; + let r = com_registration::register_com_library(); + tracing::debug!("Registered the com library: {:?}", r); + + let r = com_registration::add_authenticator(); + tracing::debug!("Added the authenticator: {:?}", r); Ok(()) } - -/// Initializes the COM library for use on the calling thread, -/// and registers + sets the security values. -fn initialize_com_library() -> std::result::Result<(), String> { - let result = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; - - if result.is_err() { - return Err(format!( - "Error: couldn't initialize the COM library\n{}", - result.message() - )); - } - - match unsafe { - CoInitializeSecurity( - None, - -1, - None, - None, - RPC_C_AUTHN_LEVEL_DEFAULT, - RPC_C_IMP_LEVEL_IMPERSONATE, - None, - EOAC_NONE, - None, - ) - } { - Ok(_) => Ok(()), - Err(e) => Err(format!( - "Error: couldn't initialize COM security\n{}", - e.message() - )), - } -} - -/// Registers the Bitwarden Plugin Authenticator COM library with Windows. -fn register_com_library() -> std::result::Result<(), String> { - static FACTORY: windows_core::StaticComObject = - pluginauthenticator::Factory().into_static(); - let clsid: *const GUID = &GUID::from_u128(0xa98925d161f640de9327dc418fcb2ff4); - - match unsafe { - CoRegisterClassObject( - clsid, - FACTORY.as_interface_ref(), - CLSCTX_LOCAL_SERVER, - REGCLS_MULTIPLEUSE, - ) - } { - Ok(_) => Ok(()), - Err(e) => Err(format!( - "Error: couldn't register the COM library\n{}", - e.message() - )), - } -} - -/// Adds Bitwarden as a plugin authenticator. -// FIXME: Remove unwraps! They panic and terminate the whole application. -#[allow(clippy::unwrap_used)] -fn add_authenticator() -> std::result::Result<(), String> { - let authenticator_name: HSTRING = AUTHENTICATOR_NAME.into(); - let authenticator_name_ptr = PCWSTR(authenticator_name.as_ptr()).as_ptr(); - - let clsid: HSTRING = format!("{{{}}}", CLSID).into(); - let clsid_ptr = PCWSTR(clsid.as_ptr()).as_ptr(); - - let relying_party_id: HSTRING = RPID.into(); - let relying_party_id_ptr = PCWSTR(relying_party_id.as_ptr()).as_ptr(); - - // let aaguid: HSTRING = format!("{{{}}}", AAGUID).into(); - // let aaguid_ptr = PCWSTR(aaguid.as_ptr()).as_ptr(); - - // Example authenticator info blob - let cbor_authenticator_info = "A60182684649444F5F325F30684649444F5F325F310282637072666B686D61632D7365637265740350D548826E79B4DB40A3D811116F7E834904A362726BF5627570F5627576F5098168696E7465726E616C0A81A263616C672664747970656A7075626C69632D6B6579"; - let mut authenticator_info_bytes = hex::decode(cbor_authenticator_info).unwrap(); - - let add_authenticator_options = webauthn::ExperimentalWebAuthnPluginAddAuthenticatorOptions { - authenticator_name: authenticator_name_ptr, - com_clsid: clsid_ptr, - rpid: relying_party_id_ptr, - light_theme_logo: ptr::null(), // unused by Windows - dark_theme_logo: ptr::null(), // unused by Windows - cbor_authenticator_info_byte_count: authenticator_info_bytes.len() as u32, - cbor_authenticator_info: authenticator_info_bytes.as_mut_ptr(), - }; - - let plugin_signing_public_key_byte_count: u32 = 0; - let mut plugin_signing_public_key: c_uchar = 0; - let plugin_signing_public_key_ptr = &mut plugin_signing_public_key; - - let mut add_response = webauthn::ExperimentalWebAuthnPluginAddAuthenticatorResponse { - plugin_operation_signing_key_byte_count: plugin_signing_public_key_byte_count, - plugin_operation_signing_key: plugin_signing_public_key_ptr, - }; - let mut add_response_ptr: *mut webauthn::ExperimentalWebAuthnPluginAddAuthenticatorResponse = - &mut add_response; - - let result = unsafe { - delay_load::( - s!("webauthn.dll"), - s!("EXPERIMENTAL_WebAuthNPluginAddAuthenticator"), - ) - }; - - match result { - Some(api) => { - let result = unsafe { api(&add_authenticator_options, &mut add_response_ptr) }; - - if result.is_err() { - return Err(format!( - "Error: Error response from EXPERIMENTAL_WebAuthNPluginAddAuthenticator()\n{}", - result.message() - )); - } - - Ok(()) - }, - None => { - Err(String::from("Error: Can't complete add_authenticator(), as the function EXPERIMENTAL_WebAuthNPluginAddAuthenticator can't be found.")) - } - } -} - -type EXPERIMENTAL_WebAuthNPluginAddAuthenticatorFnDeclaration = unsafe extern "cdecl" fn( - pPluginAddAuthenticatorOptions: *const webauthn::ExperimentalWebAuthnPluginAddAuthenticatorOptions, - ppPluginAddAuthenticatorResponse: *mut *mut webauthn::ExperimentalWebAuthnPluginAddAuthenticatorResponse, -) -> HRESULT; - -unsafe fn delay_load(library: PCSTR, function: PCSTR) -> Option { - let library = LoadLibraryExA(library, None, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); - - let Ok(library) = library else { - return None; - }; - - let address = GetProcAddress(library, function); - - if address.is_some() { - return Some(std::mem::transmute_copy(&address)); - } - - _ = FreeLibrary(library); - - None -} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/make_credential.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/make_credential.rs new file mode 100644 index 00000000000..2f263b38cac --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/make_credential.rs @@ -0,0 +1,769 @@ +use serde_json; +use std::collections::HashMap; +use std::mem::ManuallyDrop; +use std::ptr; +use std::sync::Arc; +use std::time::Duration; +use windows_core::{s, HRESULT}; + +use crate::com_provider::{ + parse_credential_list, WebAuthnPluginOperationRequest, WebAuthnPluginOperationResponse, +}; +use crate::ipc2::{ + PasskeyRegistrationRequest, PasskeyRegistrationResponse, Position, TimedCallback, + UserVerification, WindowsProviderClient, +}; +use crate::util::{debug_log, delay_load, wstr_to_string, WindowsString}; +use crate::webauthn::WEBAUTHN_CREDENTIAL_LIST; + +// Windows API types for WebAuthn (from webauthn.h.sample) +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_RP_ENTITY_INFORMATION { + pub dwVersion: u32, + pub pwszId: *const u16, // PCWSTR + pub pwszName: *const u16, // PCWSTR + pub pwszIcon: *const u16, // PCWSTR +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_USER_ENTITY_INFORMATION { + pub dwVersion: u32, + pub cbId: u32, // DWORD + pub pbId: *const u8, // PBYTE + pub pwszName: *const u16, // PCWSTR + pub pwszIcon: *const u16, // PCWSTR + pub pwszDisplayName: *const u16, // PCWSTR +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_COSE_CREDENTIAL_PARAMETER { + pub dwVersion: u32, + pub pwszCredentialType: *const u16, // LPCWSTR + pub lAlg: i32, // LONG - COSE algorithm identifier +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_COSE_CREDENTIAL_PARAMETERS { + pub cCredentialParameters: u32, + pub pCredentialParameters: *const WEBAUTHN_COSE_CREDENTIAL_PARAMETER, +} + +// Make Credential Request structure (from sample header) +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST { + pub dwVersion: u32, + pub cbRpId: u32, + pub pbRpId: *const u8, + pub cbClientDataHash: u32, + pub pbClientDataHash: *const u8, + pub pRpInformation: *const WEBAUTHN_RP_ENTITY_INFORMATION, + pub pUserInformation: *const WEBAUTHN_USER_ENTITY_INFORMATION, + pub WebAuthNCredentialParameters: WEBAUTHN_COSE_CREDENTIAL_PARAMETERS, // Matches C++ sample + pub CredentialList: WEBAUTHN_CREDENTIAL_LIST, + pub cbCborExtensionsMap: u32, + pub pbCborExtensionsMap: *const u8, + pub pAuthenticatorOptions: *const crate::webauthn::WebAuthnCtapCborAuthenticatorOptions, + // Add other fields as needed... +} + +struct WEBAUTHN_HMAC_SECRET_SALT { + /// Size of pbFirst. + cbFirst: u32, + // _Field_size_bytes_(cbFirst) + /// Required + pbFirst: *mut u8, + + /// Size of pbSecond. + cbSecond: u32, + // _Field_size_bytes_(cbSecond) + pbSecond: *mut u8, +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +struct WEBAUTHN_EXTENSION { + pwszExtensionIdentifier: *const u16, + cbExtension: u32, + pvExtension: *mut u8, +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +struct WEBAUTHN_EXTENSIONS { + cExtensions: u32, + // _Field_size_(cExtensions) + pExtensions: *mut WEBAUTHN_EXTENSION, +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +struct WEBAUTHN_CREDENTIAL_ATTESTATION { + /// Version of this structure, to allow for modifications in the future. + dwVersion: u32, + + /// Attestation format type + pwszFormatType: *const u16, // PCWSTR + + /// Size of cbAuthenticatorData. + cbAuthenticatorData: u32, + /// Authenticator data that was created for this credential. + //_Field_size_bytes_(cbAuthenticatorData) + pbAuthenticatorData: *mut u8, + + /// Size of CBOR encoded attestation information + /// 0 => encoded as CBOR null value. + cbAttestation: u32, + ///Encoded CBOR attestation information + // _Field_size_bytes_(cbAttestation) + pbAttestation: *mut u8, + + dwAttestationDecodeType: u32, + /// Following depends on the dwAttestationDecodeType + /// WEBAUTHN_ATTESTATION_DECODE_NONE + /// NULL - not able to decode the CBOR attestation information + /// WEBAUTHN_ATTESTATION_DECODE_COMMON + /// PWEBAUTHN_COMMON_ATTESTATION; + pvAttestationDecode: *mut u8, + + /// The CBOR encoded Attestation Object to be returned to the RP. + cbAttestationObject: u32, + // _Field_size_bytes_(cbAttestationObject) + pbAttestationObject: *mut u8, + + /// The CredentialId bytes extracted from the Authenticator Data. + /// Used by Edge to return to the RP. + cbCredentialId: u32, + // _Field_size_bytes_(cbCredentialId) + pbCredentialId: *mut u8, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_2 + // + /// Since VERSION 2 + Extensions: WEBAUTHN_EXTENSIONS, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_3 + // + /// One of the WEBAUTHN_CTAP_TRANSPORT_* bits will be set corresponding to + /// the transport that was used. + dwUsedTransport: u32, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_4 + // + bEpAtt: bool, + bLargeBlobSupported: bool, + bResidentKey: bool, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_5 + // + bPrfEnabled: bool, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_6 + // + cbUnsignedExtensionOutputs: u32, + // _Field_size_bytes_(cbUnsignedExtensionOutputs) + pbUnsignedExtensionOutputs: *mut u8, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_7 + // + pHmacSecret: *const WEBAUTHN_HMAC_SECRET_SALT, + + // ThirdPartyPayment Credential or not. + bThirdPartyPayment: bool, + + // + // Following fields have been added in WEBAUTHN_CREDENTIAL_ATTESTATION_VERSION_8 + // + + // Multiple WEBAUTHN_CTAP_TRANSPORT_* bits will be set corresponding to + // the transports that are supported. + dwTransports: u32, + + // UTF-8 encoded JSON serialization of the client data. + cbClientDataJSON: u32, + // _Field_size_bytes_(cbClientDataJSON) + pbClientDataJSON: *mut u8, + + // UTF-8 encoded JSON serialization of the RegistrationResponse. + cbRegistrationResponseJSON: u32, + // _Field_size_bytes_(cbRegistrationResponseJSON) + pbRegistrationResponseJSON: *mut u8, +} + +// Windows API function signatures +type WebAuthNDecodeMakeCredentialRequestFn = unsafe extern "stdcall" fn( + cbEncoded: u32, + pbEncoded: *const u8, + ppMakeCredentialRequest: *mut *mut WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST, +) -> HRESULT; + +type WebAuthNFreeDecodedMakeCredentialRequestFn = unsafe extern "stdcall" fn( + pMakeCredentialRequest: *mut WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST, +); + +type WebAuthNEncodeMakeCredentialResponseFn = unsafe extern "stdcall" fn( + cbEncoded: *const WEBAUTHN_CREDENTIAL_ATTESTATION, + pbEncoded: *mut u32, + response_bytes: *mut *mut u8, +) -> HRESULT; + +// RAII wrapper for decoded make credential request +pub struct DecodedMakeCredentialRequest { + ptr: *const WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST, + free_fn: Option, +} + +impl DecodedMakeCredentialRequest { + fn new( + ptr: *const WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST, + free_fn: Option, + ) -> Self { + Self { ptr, free_fn } + } + + pub fn as_ref(&self) -> &WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST { + unsafe { &*self.ptr } + } +} + +impl Drop for DecodedMakeCredentialRequest { + fn drop(&mut self) { + if !self.ptr.is_null() { + if let Some(free_fn) = self.free_fn { + tracing::debug!("Freeing decoded make credential request"); + unsafe { + free_fn(self.ptr as *mut WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST); + } + } + } + } +} + +// Function to decode make credential request using Windows API +unsafe fn decode_make_credential_request( + encoded_request: &[u8], +) -> Result { + tracing::debug!("Attempting to decode make credential request using Windows API"); + + // Try to load the Windows API decode function + let decode_fn = match delay_load::( + s!("webauthn.dll"), + s!("WebAuthNDecodeMakeCredentialRequest"), + ) { + Some(func) => func, + None => { + return Err( + "Failed to load WebAuthNDecodeMakeCredentialRequest from webauthn.dll".to_string(), + ); + } + }; + + // Try to load the free function (optional, might not be available in all versions) + let free_fn = delay_load::( + s!("webauthn.dll"), + s!("WebAuthNFreeDecodedMakeCredentialRequest"), + ); + + // Prepare parameters for the API call + let cb_encoded = encoded_request.len() as u32; + let pb_encoded = encoded_request.as_ptr(); + let mut make_credential_request: *mut WEBAUTHN_CTAPCBOR_MAKE_CREDENTIAL_REQUEST = + std::ptr::null_mut(); + + // Call the Windows API function + let result = decode_fn(cb_encoded, pb_encoded, &mut make_credential_request); + + // Check if the call succeeded (following C++ THROW_IF_FAILED pattern) + if result.is_err() { + debug_log(&format!( + "ERROR: WebAuthNDecodeMakeCredentialRequest failed with HRESULT: 0x{:08x}", + result.0 + )); + return Err(format!( + "Windows API call failed with HRESULT: 0x{:08x}", + result.0 + )); + } + + if make_credential_request.is_null() { + tracing::error!("Windows API succeeded but returned null pointer"); + return Err("Windows API returned null pointer".to_string()); + } + + Ok(DecodedMakeCredentialRequest::new( + make_credential_request, + free_fn, + )) +} + +/// Helper for registration requests +fn send_registration_request( + ipc_client: &WindowsProviderClient, + request: PasskeyRegistrationRequest, +) -> Result { + debug_log(&format!("Registration request data - RP ID: {}, User ID: {} bytes, User name: {}, Client data hash: {} bytes, Algorithms: {:?}, Excluded credentials: {}", + request.rp_id, request.user_handle.len(), request.user_name, request.client_data_hash.len(), request.supported_algorithms, request.excluded_credentials.len())); + + let request_json = serde_json::to_string(&request) + .map_err(|err| format!("Failed to serialize registration request: {err}"))?; + tracing::debug!("Sending registration request: {}", request_json); + let callback = Arc::new(TimedCallback::new()); + ipc_client.prepare_passkey_registration(request, callback.clone()); + let response = callback + .wait_for_response(Duration::from_secs(30)) + .map_err(|_| "Registration request timed out".to_string())? + .map_err(|err| err.to_string()); + if response.is_ok() { + tracing::debug!("Requesting credential sync after registering a new credential."); + ipc_client.send_native_status("request-sync".to_string(), "".to_string()); + } + response +} + +/// Creates a CTAP make credential response from Bitwarden's WebAuthn registration response +unsafe fn create_make_credential_response( + attestation_object: Vec, +) -> std::result::Result, HRESULT> { + use ciborium::Value; + // Use the attestation object directly as the encoded response + let att_obj_items = ciborium::from_reader::(&attestation_object[..]) + .map_err(|_| HRESULT(-1))? + .into_map() + .map_err(|_| HRESULT(-1))?; + + let webauthn_att_obj: HashMap<&str, &Value> = att_obj_items + .iter() + .map(|(k, v)| (k.as_text().unwrap(), v)) + .collect(); + + /* + let ctap_attestation_response = ciborium::Value::Map(vec![ + (Value::Integer(1.into()), webauthn_att_obj["fmt"].clone()), + ( + Value::Integer(2.into()), + webauthn_att_obj["authData"].clone(), + ), + ( + Value::Integer(3.into()), + webauthn_att_obj["attStmt"].clone(), + ), + ]); + + // Write data into CBOR + // let mut response = Vec::new(); + // ciborium::into_writer(&ctap_attestation_response, &mut response).map_err(|_| HRESULT(-1))?; + */ + + let webauthn_encode_make_credential_response = + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNEncodeMakeCredentialResponse"), + ) + .unwrap(); + let att_fmt = webauthn_att_obj + .get("fmt") + .ok_or(HRESULT(-1))? + .as_text() + .ok_or(HRESULT(-1))? + .to_utf16(); + let authenticator_data = webauthn_att_obj + .get("authData") + .ok_or(HRESULT(-1))? + .as_bytes() + .ok_or(HRESULT(-1))?; + let attestation = WEBAUTHN_CREDENTIAL_ATTESTATION { + dwVersion: 8, + pwszFormatType: att_fmt.as_ptr(), + cbAuthenticatorData: authenticator_data.len() as u32, + pbAuthenticatorData: authenticator_data.as_ptr() as *mut u8, + cbAttestation: 0, + pbAttestation: ptr::null_mut(), + dwAttestationDecodeType: 0, + pvAttestationDecode: ptr::null_mut(), + cbAttestationObject: 0, + pbAttestationObject: ptr::null_mut(), + cbCredentialId: 0, + pbCredentialId: ptr::null_mut(), + Extensions: WEBAUTHN_EXTENSIONS { + cExtensions: 0, + pExtensions: ptr::null_mut(), + }, + dwUsedTransport: 0x00000010, // INTERNAL + bEpAtt: false, + bLargeBlobSupported: false, + bResidentKey: false, + bPrfEnabled: false, + cbUnsignedExtensionOutputs: 0, + pbUnsignedExtensionOutputs: ptr::null_mut(), + pHmacSecret: ptr::null_mut(), + bThirdPartyPayment: false, + dwTransports: 0x00000030, // INTERNAL, HYBRID + cbClientDataJSON: 0, + pbClientDataJSON: ptr::null_mut(), + cbRegistrationResponseJSON: 0, + pbRegistrationResponseJSON: ptr::null_mut(), + }; + let mut response_len = 0; + let mut response_ptr = ptr::null_mut(); + let result = webauthn_encode_make_credential_response( + &attestation, + &mut response_len, + &mut response_ptr, + ); + if result.is_err() { + return Err(result); + } + let response = Vec::from_raw_parts(response_ptr, response_len as usize, response_len as usize); + + Ok(response) + /* + // Allocate memory for the response data + let layout = Layout::from_size_align(response_len as usize, 1).map_err(|_| HRESULT(-1))?; + let response_ptr = alloc(layout); + if response_ptr.is_null() { + return Err(HRESULT(-1)); + } + + // Copy response data + ptr::copy_nonoverlapping(response, response_ptr, response.len()); + + // Allocate memory for the response structure + let response_layout = Layout::new::(); + let operation_response_ptr = alloc(response_layout) as *mut WebAuthnPluginOperationResponse; + if operation_response_ptr.is_null() { + return Err(HRESULT(-1)); + } + + // Initialize the response + ptr::write( + operation_response_ptr, + WebAuthnPluginOperationResponse { + encoded_response_byte_count: response.len() as u32, + encoded_response_pointer: response_ptr, + }, + ); + tracing::debug!("CTAP-encoded attestation object: {response:?}"); + Ok(operation_response_ptr) + */ +} + +/// Implementation of PluginMakeCredential moved from com_provider.rs +pub unsafe fn plugin_make_credential( + ipc_client: &WindowsProviderClient, + request: *const WebAuthnPluginOperationRequest, + response: *mut WebAuthnPluginOperationResponse, +) -> Result<(), HRESULT> { + tracing::debug!("=== PluginMakeCredential() called ==="); + + if request.is_null() { + tracing::error!("NULL request pointer"); + return Err(HRESULT(-1)); + } + + if response.is_null() { + tracing::error!("NULL response pointer"); + return Err(HRESULT(-1)); + } + + let req = &*request; + let transaction_id = format!("{:?}", req.transaction_id); + + let coords = req.window_coordinates().unwrap_or((400, 400)); + + if req.encoded_request_byte_count == 0 || req.encoded_request_pointer.is_null() { + tracing::error!("No encoded request data provided"); + return Err(HRESULT(-1)); + } + + let encoded_request_slice = std::slice::from_raw_parts( + req.encoded_request_pointer, + req.encoded_request_byte_count as usize, + ); + + debug_log(&format!( + "Encoded request: {} bytes", + encoded_request_slice.len() + )); + + // Try to decode the request using Windows API + let decoded_wrapper = decode_make_credential_request(encoded_request_slice).map_err(|err| { + debug_log(&format!( + "ERROR: Failed to decode make credential request: {err}" + )); + HRESULT(-1) + })?; + let decoded_request = decoded_wrapper.as_ref(); + tracing::debug!("Successfully decoded make credential request using Windows API"); + + // Extract RP information + if decoded_request.pRpInformation.is_null() { + tracing::error!("RP information is null"); + return Err(HRESULT(-1)); + } + + let rp_info = &*decoded_request.pRpInformation; + + let rpid = if rp_info.pwszId.is_null() { + tracing::error!("RP ID is null"); + return Err(HRESULT(-1)); + } else { + match wstr_to_string(rp_info.pwszId) { + Ok(id) => id, + Err(e) => { + tracing::error!("Failed to decode RP ID: {}", e); + return Err(HRESULT(-1)); + } + } + }; + + // let rp_name = if rp_info.pwszName.is_null() { + // String::new() + // } else { + // wstr_to_string(rp_info.pwszName).unwrap_or_default() + // }; + + // Extract user information + if decoded_request.pUserInformation.is_null() { + tracing::error!("User information is null"); + return Err(HRESULT(-1)); + } + + let user = &*decoded_request.pUserInformation; + + let user_id = if user.pbId.is_null() || user.cbId == 0 { + tracing::error!("User ID is required for registration"); + return Err(HRESULT(-1)); + } else { + let id_slice = std::slice::from_raw_parts(user.pbId, user.cbId as usize); + id_slice.to_vec() + }; + + let user_name = if user.pwszName.is_null() { + tracing::error!("User name is required for registration"); + return Err(HRESULT(-1)); + } else { + match wstr_to_string(user.pwszName) { + Ok(name) => name, + Err(_) => { + tracing::error!("Failed to decode user name"); + return Err(HRESULT(-1)); + } + } + }; + + let user_display_name = if user.pwszDisplayName.is_null() { + None + } else { + wstr_to_string(user.pwszDisplayName).ok() + }; + + let user_info = (user_id, user_name, user_display_name); + + // Extract client data hash + let client_data_hash = + if decoded_request.cbClientDataHash == 0 || decoded_request.pbClientDataHash.is_null() { + tracing::error!("Client data hash is required for registration"); + return Err(HRESULT(-1)); + } else { + let hash_slice = std::slice::from_raw_parts( + decoded_request.pbClientDataHash, + decoded_request.cbClientDataHash as usize, + ); + hash_slice.to_vec() + }; + + // Extract supported algorithms + let supported_algorithms = if decoded_request + .WebAuthNCredentialParameters + .cCredentialParameters + > 0 + && !decoded_request + .WebAuthNCredentialParameters + .pCredentialParameters + .is_null() + { + let params_count = decoded_request + .WebAuthNCredentialParameters + .cCredentialParameters as usize; + let params_ptr = decoded_request + .WebAuthNCredentialParameters + .pCredentialParameters; + + (0..params_count) + .map(|i| unsafe { &*params_ptr.add(i) }.lAlg) + .collect() + } else { + Vec::new() + }; + + // Extract user verification requirement from authenticator options + let user_verification = if !decoded_request.pAuthenticatorOptions.is_null() { + let auth_options = &*decoded_request.pAuthenticatorOptions; + match auth_options.user_verification { + 1 => UserVerification::Required, + -1 => UserVerification::Discouraged, + 0 | _ => UserVerification::Preferred, // Default or undefined + } + } else { + UserVerification::Preferred // Default or undefined + }; + + // Extract excluded credentials from credential list + let excluded_credentials = parse_credential_list(&decoded_request.CredentialList); + if !excluded_credentials.is_empty() { + debug_log(&format!( + "Found {} excluded credentials for make credential", + excluded_credentials.len() + )); + } + + // Create Windows registration request + let registration_request = PasskeyRegistrationRequest { + rp_id: rpid.clone(), + user_handle: user_info.0, + user_name: user_info.1, + // user_display_name: user_info.2, + client_data_hash, + excluded_credentials, + user_verification: user_verification, + supported_algorithms, + window_xy: Position { + x: coords.0, + y: coords.1, + }, + }; + + debug_log(&format!( + "Make credential request - RP: {}, User: {}", + rpid, registration_request.user_name + )); + + // Send registration request + let passkey_response = + send_registration_request(ipc_client, registration_request).map_err(|err| { + tracing::error!("Registration request failed: {err}"); + HRESULT(-1) + })?; + debug_log(&format!( + "Registration response received: {:?}", + passkey_response + )); + + // Create proper WebAuthn response from passkey_response + tracing::debug!("Creating WebAuthn make credential response"); + let mut webauthn_response = + create_make_credential_response(passkey_response.attestation_object).map_err(|err| { + tracing::error!("Failed to create WebAuthn response: {err}"); + HRESULT(-1) + })?; + debug_log(&format!( + "Successfully created WebAuthn response: {webauthn_response:?}" + )); + (*response).encoded_response_byte_count = webauthn_response.len() as u32; + (*response).encoded_response_pointer = webauthn_response.as_mut_ptr(); + tracing::debug!("Set pointer, returning HRESULT(0)"); + _ = ManuallyDrop::new(webauthn_response); + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::ptr; + + use windows_core::s; + + use crate::{ + make_credential::{ + create_make_credential_response, WebAuthNEncodeMakeCredentialResponseFn, + WEBAUTHN_CREDENTIAL_ATTESTATION, WEBAUTHN_EXTENSIONS, + }, + util::{delay_load, WindowsString}, + }; + #[test] + fn test_encode_make_credential_custom() { + let webauthn_att_obj = vec![ + 163, 99, 102, 109, 116, 100, 110, 111, 110, 101, 103, 97, 116, 116, 83, 116, 109, 116, + 160, 104, 97, 117, 116, 104, 68, 97, 116, 97, 68, 1, 2, 3, 4, + ]; + /* + 148, 116, 166, 234, 146, 19, 201, + 156, 47, 116, 178, 36, 146, 179, 32, 207, 64, 38, 42, 148, 193, 169, 80, 160, 57, 127, + 41, 37, 11, 96, 132, 30, 240, 93, 0, 0, 0, 0, 213, 72, 130, 110, 121, 180, 219, 64, + 163, 216, 17, 17, 111, 126, 131, 73, 0, 16, 41, 58, 58, 242, 229, 31, 75, 22, 168, 253, + 151, 122, 177, 155, 237, 89, 165, 1, 2, 3, 38, 32, 1, 33, 88, 32, 154, 18, 243, 88, 48, + 112, 84, 3, 82, 219, 172, 210, 76, 151, 246, 101, 189, 86, 147, 114, 248, 43, 231, 192, + 202, 190, 92, 37, 216, 45, 202, 250, 34, 88, 32, 28, 36, 149, 44, 106, 229, 243, 164, + 190, 234, 102, 125, 168, 224, 155, 182, 190, 178, 218, 158, 98, 11, 57, 187, 41, 10, + 218, 58, 80, 124, 254, 119, + ]; + */ + let ctap_att_obj = unsafe { create_make_credential_response(webauthn_att_obj).unwrap() }; + println!("{ctap_att_obj:?}"); + let expected = vec![163, 1, 100, 110, 111, 110, 101, 2, 68, 1, 2, 3, 4, 3, 160]; + assert_eq!(expected, ctap_att_obj); + } + + #[test] + fn test_encode_make_credential() { + let response = unsafe { + let webauthn_encode_make_credential_response = + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNEncodeMakeCredentialResponse"), + ) + .unwrap(); + let mut authenticator_data = vec![1, 2, 3, 4]; + let att_fmt = "none".to_utf16(); + let attestation = WEBAUTHN_CREDENTIAL_ATTESTATION { + dwVersion: 8, + pwszFormatType: att_fmt.as_ptr(), + cbAuthenticatorData: authenticator_data.len() as u32, + pbAuthenticatorData: authenticator_data.as_mut_ptr(), + cbAttestation: 0, + pbAttestation: ptr::null_mut(), + dwAttestationDecodeType: 0, + pvAttestationDecode: ptr::null_mut(), + cbAttestationObject: 0, + pbAttestationObject: ptr::null_mut(), + cbCredentialId: 0, + pbCredentialId: ptr::null_mut(), + Extensions: WEBAUTHN_EXTENSIONS { + cExtensions: 0, + pExtensions: ptr::null_mut(), + }, + dwUsedTransport: 0x00000010, // INTERNAL + bEpAtt: false, + bLargeBlobSupported: false, + bResidentKey: false, + bPrfEnabled: false, + cbUnsignedExtensionOutputs: 0, + pbUnsignedExtensionOutputs: ptr::null_mut(), + pHmacSecret: ptr::null_mut(), + bThirdPartyPayment: false, + dwTransports: 0x00000030, // INTERNAL, HYBRID + cbClientDataJSON: 0, + pbClientDataJSON: ptr::null_mut(), + cbRegistrationResponseJSON: 0, + pbRegistrationResponseJSON: ptr::null_mut(), + }; + let mut len = 0; + let mut response_ptr = ptr::null_mut(); + let result = + webauthn_encode_make_credential_response(&attestation, &mut len, &mut response_ptr); + assert!(result.is_ok()); + Vec::from_raw_parts(response_ptr, len as usize, len as usize) + }; + println!("{response:?}"); + assert_eq!(165, response[0]); + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/pluginauthenticator.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/pluginauthenticator.rs deleted file mode 100644 index 132f9effcde..00000000000 --- a/apps/desktop/desktop_native/windows_plugin_authenticator/src/pluginauthenticator.rs +++ /dev/null @@ -1,110 +0,0 @@ -/* - This file exposes the functions and types defined here: https://github.com/microsoft/webauthn/blob/master/experimental/pluginauthenticator.h -*/ - -use windows::Win32::System::Com::*; -use windows_core::*; - -/// Used when creating and asserting credentials. -/// Header File Name: _EXPERIMENTAL_WEBAUTHN_PLUGIN_OPERATION_REQUEST -/// Header File Usage: EXPERIMENTAL_PluginMakeCredential() -/// EXPERIMENTAL_PluginGetAssertion() -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct ExperimentalWebAuthnPluginOperationRequest { - pub window_handle: windows::Win32::Foundation::HWND, - pub transaction_id: windows_core::GUID, - pub request_signature_byte_count: u32, - pub request_signature_pointer: *mut u8, - pub encoded_request_byte_count: u32, - pub encoded_request_pointer: *mut u8, -} - -/// Used as a response when creating and asserting credentials. -/// Header File Name: _EXPERIMENTAL_WEBAUTHN_PLUGIN_OPERATION_RESPONSE -/// Header File Usage: EXPERIMENTAL_PluginMakeCredential() -/// EXPERIMENTAL_PluginGetAssertion() -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct ExperimentalWebAuthnPluginOperationResponse { - pub encoded_response_byte_count: u32, - pub encoded_response_pointer: *mut u8, -} - -/// Used to cancel an operation. -/// Header File Name: _EXPERIMENTAL_WEBAUTHN_PLUGIN_CANCEL_OPERATION_REQUEST -/// Header File Usage: EXPERIMENTAL_PluginCancelOperation() -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct ExperimentalWebAuthnPluginCancelOperationRequest { - pub transaction_id: windows_core::GUID, - pub request_signature_byte_count: u32, - pub request_signature_pointer: *mut u8, -} - -#[interface("e6466e9a-b2f3-47c5-b88d-89bc14a8d998")] -pub unsafe trait EXPERIMENTAL_IPluginAuthenticator: IUnknown { - fn EXPERIMENTAL_PluginMakeCredential( - &self, - request: *const ExperimentalWebAuthnPluginOperationRequest, - response: *mut ExperimentalWebAuthnPluginOperationResponse, - ) -> HRESULT; - fn EXPERIMENTAL_PluginGetAssertion( - &self, - request: *const ExperimentalWebAuthnPluginOperationRequest, - response: *mut ExperimentalWebAuthnPluginOperationResponse, - ) -> HRESULT; - fn EXPERIMENTAL_PluginCancelOperation( - &self, - request: *const ExperimentalWebAuthnPluginCancelOperationRequest, - ) -> HRESULT; -} - -#[implement(EXPERIMENTAL_IPluginAuthenticator)] -pub struct PluginAuthenticatorComObject; - -#[implement(IClassFactory)] -pub struct Factory(); - -impl EXPERIMENTAL_IPluginAuthenticator_Impl for PluginAuthenticatorComObject_Impl { - unsafe fn EXPERIMENTAL_PluginMakeCredential( - &self, - _request: *const ExperimentalWebAuthnPluginOperationRequest, - _response: *mut ExperimentalWebAuthnPluginOperationResponse, - ) -> HRESULT { - HRESULT(0) - } - - unsafe fn EXPERIMENTAL_PluginGetAssertion( - &self, - _request: *const ExperimentalWebAuthnPluginOperationRequest, - _response: *mut ExperimentalWebAuthnPluginOperationResponse, - ) -> HRESULT { - HRESULT(0) - } - - unsafe fn EXPERIMENTAL_PluginCancelOperation( - &self, - _request: *const ExperimentalWebAuthnPluginCancelOperationRequest, - ) -> HRESULT { - HRESULT(0) - } -} - -impl IClassFactory_Impl for Factory_Impl { - fn CreateInstance( - &self, - outer: Ref, - iid: *const GUID, - object: *mut *mut core::ffi::c_void, - ) -> Result<()> { - assert!(outer.is_null()); - let unknown: IInspectable = PluginAuthenticatorComObject.into(); - unsafe { unknown.query(iid, object).ok() } - } - - fn LockServer(&self, lock: BOOL) -> Result<()> { - assert!(lock.as_bool()); - Ok(()) - } -} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/types.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/types.rs new file mode 100644 index 00000000000..f64a73478f8 --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/types.rs @@ -0,0 +1,35 @@ +/// User verification requirement as defined by WebAuthn spec +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum UserVerificationRequirement { + Required, + Preferred, + Discouraged, +} + +impl Default for UserVerificationRequirement { + fn default() -> Self { + UserVerificationRequirement::Preferred + } +} + +impl From for UserVerificationRequirement { + fn from(value: u32) -> Self { + match value { + 1 => UserVerificationRequirement::Required, + 2 => UserVerificationRequirement::Preferred, + 3 => UserVerificationRequirement::Discouraged, + _ => UserVerificationRequirement::Preferred, // Default fallback + } + } +} + +impl Into for UserVerificationRequirement { + fn into(self) -> String { + match self { + UserVerificationRequirement::Required => "required".to_string(), + UserVerificationRequirement::Preferred => "preferred".to_string(), + UserVerificationRequirement::Discouraged => "discouraged".to_string(), + } + } +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/util.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/util.rs new file mode 100644 index 00000000000..d4ff50037bf --- /dev/null +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/util.rs @@ -0,0 +1,102 @@ +use std::fs::{create_dir_all, OpenOptions}; +use std::io::Write; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use windows::Win32::Foundation::*; +use windows::Win32::System::LibraryLoader::*; +use windows_core::*; + +use crate::com_buffer::ComBuffer; + +pub unsafe fn delay_load(library: PCSTR, function: PCSTR) -> Option { + let library = LoadLibraryExA(library, None, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + + let Ok(library) = library else { + return None; + }; + + let address = GetProcAddress(library, function); + + if address.is_some() { + return Some(std::mem::transmute_copy(&address)); + } + + _ = FreeLibrary(library); + + None +} + +/// Trait for converting strings to Windows-compatible wide strings using COM allocation +pub trait WindowsString { + /// Converts to null-terminated UTF-16 using COM allocation + fn to_com_utf16(&self) -> (*mut u16, u32); + /// Converts to Vec for temporary use (caller must keep Vec alive) + fn to_utf16(&self) -> Vec; +} + +impl WindowsString for str { + fn to_com_utf16(&self) -> (*mut u16, u32) { + let mut wide_vec: Vec = self.encode_utf16().collect(); + wide_vec.push(0); // null terminator + let wide_bytes: Vec = wide_vec.iter().flat_map(|&x| x.to_le_bytes()).collect(); + let (ptr, byte_count) = ComBuffer::from_buffer(&wide_bytes); + (ptr as *mut u16, byte_count) + } + + fn to_utf16(&self) -> Vec { + let mut wide_vec: Vec = self.encode_utf16().collect(); + wide_vec.push(0); // null terminator + wide_vec + } +} + +pub fn file_log(msg: &str) { + let log_path = "C:\\temp\\bitwarden_com_debug.log"; + + // Create the temp directory if it doesn't exist + if let Some(parent) = Path::new(log_path).parent() { + let _ = create_dir_all(parent); + } + + if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) { + let now = SystemTime::now(); + let timestamp = match now.duration_since(UNIX_EPOCH) { + Ok(duration) => { + let total_secs = duration.as_secs(); + let millis = duration.subsec_millis(); + let secs = total_secs % 60; + let mins = (total_secs / 60) % 60; + let hours = (total_secs / 3600) % 24; + format!("{:02}:{:02}:{:02}.{:03}", hours, mins, secs, millis) + } + Err(_) => "??:??:??.???".to_string(), + }; + + let _ = writeln!(file, "[{}] {}", timestamp, msg); + } +} + +pub fn debug_log(message: &str) { + tracing::debug!(message); + file_log(message) +} + +// Helper function to convert Windows wide string (UTF-16) to Rust String +pub unsafe fn wstr_to_string( + wstr_ptr: *const u16, +) -> std::result::Result { + if wstr_ptr.is_null() { + return Ok(String::new()); + } + + // Find the length of the null-terminated wide string + let mut len = 0; + while *wstr_ptr.add(len) != 0 { + len += 1; + } + + // Convert to Rust string + let wide_slice = std::slice::from_raw_parts(wstr_ptr, len); + String::from_utf16(wide_slice) +} diff --git a/apps/desktop/desktop_native/windows_plugin_authenticator/src/webauthn.rs b/apps/desktop/desktop_native/windows_plugin_authenticator/src/webauthn.rs index 18c7563ffd8..c43c1559a26 100644 --- a/apps/desktop/desktop_native/windows_plugin_authenticator/src/webauthn.rs +++ b/apps/desktop/desktop_native/windows_plugin_authenticator/src/webauthn.rs @@ -1,29 +1,418 @@ /* - This file exposes the functions and types defined here: https://github.com/microsoft/webauthn/blob/master/experimental/webauthn.h + This file exposes safe functions and types for interacting with the stable + Windows WebAuthn Plugin API defined here: + + https://github.com/microsoft/webauthn/blob/master/webauthnplugin.h */ -/// Used when adding a Windows plugin authenticator. -/// Header File Name: _EXPERIMENTAL_WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS -/// Header File Usage: EXPERIMENTAL_WebAuthNPluginAddAuthenticator() +use windows_core::*; + +use crate::com_buffer::ComBuffer; +use crate::util::{debug_log, delay_load, WindowsString}; + +/// Windows WebAuthn Authenticator Options structure +/// Header File Name: _WEBAUTHN_CTAPCBOR_AUTHENTICATOR_OPTIONS #[repr(C)] #[derive(Debug, Copy, Clone)] -pub struct ExperimentalWebAuthnPluginAddAuthenticatorOptions { - pub authenticator_name: *const u16, - pub com_clsid: *const u16, - pub rpid: *const u16, - pub light_theme_logo: *const u16, - pub dark_theme_logo: *const u16, - pub cbor_authenticator_info_byte_count: u32, - pub cbor_authenticator_info: *const u8, +pub struct WebAuthnCtapCborAuthenticatorOptions { + pub version: u32, // DWORD dwVersion + pub user_presence: i32, // LONG lUp: +1=TRUE, 0=Not defined, -1=FALSE + pub user_verification: i32, // LONG lUv: +1=TRUE, 0=Not defined, -1=FALSE + pub require_resident_key: i32, // LONG lRequireResidentKey: +1=TRUE, 0=Not defined, -1=FALSE } -/// Used as a response type when adding a Windows plugin authenticator. -/// Header File Name: _EXPERIMENTAL_WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE -/// Header File Usage: EXPERIMENTAL_WebAuthNPluginAddAuthenticator() -/// EXPERIMENTAL_WebAuthNPluginFreeAddAuthenticatorResponse() +/// Used when adding a Windows plugin authenticator (stable API). +/// Header File Name: _WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_OPTIONS +/// Header File Usage: WebAuthNPluginAddAuthenticator() #[repr(C)] #[derive(Debug, Copy, Clone)] -pub struct ExperimentalWebAuthnPluginAddAuthenticatorResponse { +pub struct WebAuthnPluginAddAuthenticatorOptions { + pub authenticator_name: *const u16, // LPCWSTR + pub rclsid: *const GUID, // REFCLSID (changed from string) + pub rpid: *const u16, // LPCWSTR (optional) + pub light_theme_logo_svg: *const u16, // LPCWSTR (optional, base64 SVG) + pub dark_theme_logo_svg: *const u16, // LPCWSTR (optional, base64 SVG) + pub cbor_authenticator_info_byte_count: u32, + pub cbor_authenticator_info: *const u8, // const BYTE* + pub supported_rp_ids_count: u32, // NEW in stable + pub supported_rp_ids: *const *const u16, // NEW in stable: array of LPCWSTR +} + +/// Used as a response type when adding a Windows plugin authenticator (stable API). +/// Header File Name: _WEBAUTHN_PLUGIN_ADD_AUTHENTICATOR_RESPONSE +/// Header File Usage: WebAuthNPluginAddAuthenticator() +/// WebAuthNPluginFreeAddAuthenticatorResponse() +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WebAuthnPluginAddAuthenticatorResponse { pub plugin_operation_signing_key_byte_count: u32, pub plugin_operation_signing_key: *mut u8, } + +/// Represents a credential. +/// Header File Name: _WEBAUTHN_PLUGIN_CREDENTIAL_DETAILS +/// Header File Usage: WebAuthNPluginAuthenticatorAddCredentials, etc. +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WebAuthnPluginCredentialDetails { + pub credential_id_byte_count: u32, + pub credential_id_pointer: *const u8, // Changed to const in stable + pub rpid: *const u16, // Changed to const (LPCWSTR) + pub rp_friendly_name: *const u16, // Changed to const (LPCWSTR) + pub user_id_byte_count: u32, + pub user_id_pointer: *const u8, // Changed to const + pub user_name: *const u16, // Changed to const (LPCWSTR) + pub user_display_name: *const u16, // Changed to const (LPCWSTR) +} + +impl WebAuthnPluginCredentialDetails { + pub fn create_from_bytes( + credential_id: Vec, + rpid: String, + rp_friendly_name: String, + user_id: Vec, + user_name: String, + user_display_name: String, + ) -> Self { + // Allocate credential_id bytes with COM + let (credential_id_pointer, credential_id_byte_count) = + ComBuffer::from_buffer(&credential_id); + + // Allocate user_id bytes with COM + let (user_id_pointer, user_id_byte_count) = ComBuffer::from_buffer(&user_id); + + // Convert strings to null-terminated wide strings using trait methods + let (rpid_ptr, _) = rpid.to_com_utf16(); + let (rp_friendly_name_ptr, _) = rp_friendly_name.to_com_utf16(); + let (user_name_ptr, _) = user_name.to_com_utf16(); + let (user_display_name_ptr, _) = user_display_name.to_com_utf16(); + + Self { + credential_id_byte_count, + credential_id_pointer: credential_id_pointer as *const u8, + rpid: rpid_ptr as *const u16, + rp_friendly_name: rp_friendly_name_ptr as *const u16, + user_id_byte_count, + user_id_pointer: user_id_pointer as *const u8, + user_name: user_name_ptr as *const u16, + user_display_name: user_display_name_ptr as *const u16, + } + } +} + +// Stable API function signatures - now use REFCLSID and flat arrays +pub type WebAuthNPluginAuthenticatorAddCredentialsFnDeclaration = + unsafe extern "cdecl" fn( + rclsid: *const GUID, // Changed from string to GUID reference + cCredentialDetails: u32, + pCredentialDetails: *const WebAuthnPluginCredentialDetails, // Flat array, not list + ) -> HRESULT; + +pub type WebAuthNPluginAuthenticatorRemoveCredentialsFnDeclaration = + unsafe extern "cdecl" fn( + rclsid: *const GUID, + cCredentialDetails: u32, + pCredentialDetails: *const WebAuthnPluginCredentialDetails, + ) -> HRESULT; + +pub type WebAuthNPluginAuthenticatorGetAllCredentialsFnDeclaration = + unsafe extern "cdecl" fn( + rclsid: *const GUID, + pcCredentialDetails: *mut u32, // Out param for count + ppCredentialDetailsArray: *mut *mut WebAuthnPluginCredentialDetails, // Out param for array + ) -> HRESULT; + +pub type WebAuthNPluginAuthenticatorFreeCredentialDetailsArrayFnDeclaration = + unsafe extern "cdecl" fn( + cCredentialDetails: u32, + pCredentialDetailsArray: *mut WebAuthnPluginCredentialDetails, + ); + +pub type WebAuthNPluginAuthenticatorRemoveAllCredentialsFnDeclaration = + unsafe extern "cdecl" fn(rclsid: *const GUID) -> HRESULT; + +pub fn add_credentials( + clsid_guid: GUID, + credentials: Vec, +) -> std::result::Result<(), String> { + debug_log("Loading WebAuthNPluginAuthenticatorAddCredentials function..."); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorAddCredentials"), + ) + }; + + match result { + Some(api) => { + debug_log("Function loaded successfully, calling API..."); + debug_log(&format!("Adding {} credentials", credentials.len())); + + let credential_count = credentials.len() as u32; + let credentials_ptr = if credentials.is_empty() { + std::ptr::null() + } else { + credentials.as_ptr() + }; + + let result = unsafe { api(&clsid_guid, credential_count, credentials_ptr) }; + + if result.is_err() { + let error_code = result.0; + debug_log(&format!("API call failed with HRESULT: 0x{:x}", error_code)); + return Err(format!( + "Error: Error response from WebAuthNPluginAuthenticatorAddCredentials()\nHRESULT: 0x{:x}\n{}", + error_code, result.message() + )); + } + + debug_log("API call succeeded"); + Ok(()) + } + None => { + debug_log("Failed to load WebAuthNPluginAuthenticatorAddCredentials function from webauthn.dll"); + Err(String::from("Error: Can't complete add_credentials(), as the function WebAuthNPluginAuthenticatorAddCredentials can't be loaded.")) + } + } +} + +pub fn remove_credentials( + clsid_guid: GUID, + credentials: Vec, +) -> std::result::Result<(), String> { + debug_log("Loading WebAuthNPluginAuthenticatorRemoveCredentials function..."); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorRemoveCredentials"), + ) + }; + + match result { + Some(api) => { + debug_log(&format!("Removing {} credentials", credentials.len())); + + let credential_count = credentials.len() as u32; + let credentials_ptr = if credentials.is_empty() { + std::ptr::null() + } else { + credentials.as_ptr() + }; + + let result = unsafe { api(&clsid_guid, credential_count, credentials_ptr) }; + + if result.is_err() { + return Err(format!( + "Error: Error response from WebAuthNPluginAuthenticatorRemoveCredentials()\n{}", + result.message() + )); + } + + Ok(()) + }, + None => { + Err(String::from("Error: Can't complete remove_credentials(), as the function WebAuthNPluginAuthenticatorRemoveCredentials can't be loaded.")) + } + } +} + +// Helper struct to hold owned credential data +#[derive(Debug, Clone)] +pub struct OwnedCredentialDetails { + pub credential_id: Vec, + pub rpid: String, + pub rp_friendly_name: String, + pub user_id: Vec, + pub user_name: String, + pub user_display_name: String, +} + +pub fn get_all_credentials( + clsid_guid: GUID, +) -> std::result::Result, String> { + debug_log("Loading WebAuthNPluginAuthenticatorGetAllCredentials function..."); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorGetAllCredentials"), + ) + }; + + match result { + Some(api) => { + let mut credential_count: u32 = 0; + let mut credentials_array_ptr: *mut WebAuthnPluginCredentialDetails = std::ptr::null_mut(); + + let result = unsafe { api(&clsid_guid, &mut credential_count, &mut credentials_array_ptr) }; + + if result.is_err() { + return Err(format!( + "Error: Error response from WebAuthNPluginAuthenticatorGetAllCredentials()\n{}", + result.message() + )); + } + + if credentials_array_ptr.is_null() || credential_count == 0 { + debug_log("No credentials returned"); + return Ok(Vec::new()); + } + + // Deep copy the credential data before Windows frees it + let credentials_slice = unsafe { + std::slice::from_raw_parts(credentials_array_ptr, credential_count as usize) + }; + + let mut owned_credentials = Vec::new(); + for cred in credentials_slice { + unsafe { + // Copy credential ID bytes + let credential_id = if !cred.credential_id_pointer.is_null() && cred.credential_id_byte_count > 0 { + std::slice::from_raw_parts(cred.credential_id_pointer, cred.credential_id_byte_count as usize).to_vec() + } else { + Vec::new() + }; + + // Copy user ID bytes + let user_id = if !cred.user_id_pointer.is_null() && cred.user_id_byte_count > 0 { + std::slice::from_raw_parts(cred.user_id_pointer, cred.user_id_byte_count as usize).to_vec() + } else { + Vec::new() + }; + + // Copy string fields + let rpid = if !cred.rpid.is_null() { + String::from_utf16_lossy(std::slice::from_raw_parts( + cred.rpid, + (0..).position(|i| *cred.rpid.offset(i) == 0).unwrap_or(0) + )) + } else { + String::new() + }; + + let rp_friendly_name = if !cred.rp_friendly_name.is_null() { + String::from_utf16_lossy(std::slice::from_raw_parts( + cred.rp_friendly_name, + (0..).position(|i| *cred.rp_friendly_name.offset(i) == 0).unwrap_or(0) + )) + } else { + String::new() + }; + + let user_name = if !cred.user_name.is_null() { + String::from_utf16_lossy(std::slice::from_raw_parts( + cred.user_name, + (0..).position(|i| *cred.user_name.offset(i) == 0).unwrap_or(0) + )) + } else { + String::new() + }; + + let user_display_name = if !cred.user_display_name.is_null() { + String::from_utf16_lossy(std::slice::from_raw_parts( + cred.user_display_name, + (0..).position(|i| *cred.user_display_name.offset(i) == 0).unwrap_or(0) + )) + } else { + String::new() + }; + + owned_credentials.push(OwnedCredentialDetails { + credential_id, + rpid, + rp_friendly_name, + user_id, + user_name, + user_display_name, + }); + } + } + + // Free the array using the Windows API - this frees everything including strings + free_credential_details_array(credential_count, credentials_array_ptr); + + debug_log(&format!("Retrieved {} credentials", owned_credentials.len())); + Ok(owned_credentials) + }, + None => { + Err(String::from("Error: Can't complete get_all_credentials(), as the function WebAuthNPluginAuthenticatorGetAllCredentials can't be loaded.")) + } + } +} + +fn free_credential_details_array( + credential_count: u32, + credentials_array: *mut WebAuthnPluginCredentialDetails, +) { + if credentials_array.is_null() { + return; + } + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorFreeCredentialDetailsArray"), + ) + }; + + if let Some(api) = result { + unsafe { api(credential_count, credentials_array) }; + } else { + debug_log("Warning: Could not load WebAuthNPluginAuthenticatorFreeCredentialDetailsArray"); + } +} + +pub fn remove_all_credentials(clsid_guid: GUID) -> std::result::Result<(), String> { + debug_log("Loading WebAuthNPluginAuthenticatorRemoveAllCredentials function..."); + + let result = unsafe { + delay_load::( + s!("webauthn.dll"), + s!("WebAuthNPluginAuthenticatorRemoveAllCredentials"), + ) + }; + + match result { + Some(api) => { + debug_log("Function loaded successfully, calling API..."); + + let result = unsafe { api(&clsid_guid) }; + + if result.is_err() { + let error_code = result.0; + debug_log(&format!("API call failed with HRESULT: 0x{:x}", error_code)); + + return Err(format!( + "Error: Error response from WebAuthNPluginAuthenticatorRemoveAllCredentials()\nHRESULT: 0x{:x}\n{}", + error_code, result.message() + )); + } + + debug_log("API call succeeded"); + Ok(()) + } + None => { + debug_log("Failed to load WebAuthNPluginAuthenticatorRemoveAllCredentials function from webauthn.dll"); + Err(String::from("Error: Can't complete remove_all_credentials(), as the function WebAuthNPluginAuthenticatorRemoveAllCredentials can't be loaded.")) + } + } +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_CREDENTIAL_EX { + pub dwVersion: u32, + pub cbId: u32, + pub pbId: *const u8, + pub pwszCredentialType: *const u16, // LPCWSTR + pub dwTransports: u32, +} + +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct WEBAUTHN_CREDENTIAL_LIST { + pub cCredentials: u32, + pub ppCredentials: *const *const WEBAUTHN_CREDENTIAL_EX, +} diff --git a/apps/desktop/electron-builder.beta.json b/apps/desktop/electron-builder.beta.json index 630a956560d..71850804cbd 100644 --- a/apps/desktop/electron-builder.beta.json +++ b/apps/desktop/electron-builder.beta.json @@ -20,7 +20,7 @@ "**/node_modules/@bitwarden/desktop-napi/index.js", "**/node_modules/@bitwarden/desktop-napi/desktop_napi.${platform}-${arch}*.node" ], - "electronVersion": "36.8.1", + "electronVersion": "36.9.3", "generateUpdatesFilesForAllChannels": true, "publish": { "provider": "generic", @@ -58,9 +58,10 @@ "appx": { "artifactName": "Bitwarden-Beta-${version}-${arch}.${ext}", "backgroundColor": "#175DDC", + "customManifestPath": "./custom-appx-manifest.xml", "applicationId": "BitwardenBeta", "identityName": "8bitSolutionsLLC.BitwardenBeta", - "publisher": "CN=14D52771-DE3C-4886-B8BF-825BA7690418", + "publisher": "CN=Bitwarden Inc., O=Bitwarden Inc., L=Santa Barbara, S=California, C=US, SERIALNUMBER=7654941, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US", "publisherDisplayName": "Bitwarden Inc", "languages": [ "en-US", diff --git a/apps/desktop/electron-builder.json b/apps/desktop/electron-builder.json index 0b18786863d..0bd6d93970b 100644 --- a/apps/desktop/electron-builder.json +++ b/apps/desktop/electron-builder.json @@ -1,4 +1,6 @@ { + "$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json", + "extraMetadata": { "name": "bitwarden" }, @@ -90,7 +92,8 @@ "electronUpdaterCompatibility": ">=0.0.1", "target": ["portable", "nsis-web", "appx"], "signtoolOptions": { - "sign": "./sign.js" + "sign": "./sign.js", + "publisherName": "CN=com.bitwarden.localdevelopment" }, "extraFiles": [ { @@ -172,9 +175,10 @@ "appx": { "artifactName": "${productName}-${version}-${arch}.${ext}", "backgroundColor": "#175DDC", + "customManifestPath": "./custom-appx-manifest.xml", "applicationId": "bitwardendesktop", "identityName": "8bitSolutionsLLC.bitwardendesktop", - "publisher": "CN=14D52771-DE3C-4886-B8BF-825BA7690418", + "publisher": "CN=Bitwarden Inc., O=Bitwarden Inc., L=Santa Barbara, S=California, C=US, SERIALNUMBER=7654941, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US", "publisherDisplayName": "Bitwarden Inc", "languages": [ "en-US", diff --git a/apps/desktop/macos/autofill-extension/Base.lproj/CredentialProviderViewController.xib b/apps/desktop/macos/autofill-extension/Base.lproj/CredentialProviderViewController.xib index 1e47cc54de2..132882c6477 100644 --- a/apps/desktop/macos/autofill-extension/Base.lproj/CredentialProviderViewController.xib +++ b/apps/desktop/macos/autofill-extension/Base.lproj/CredentialProviderViewController.xib @@ -8,63 +8,56 @@ + + + + + diff --git a/apps/desktop/macos/autofill-extension/CredentialProviderViewController.swift b/apps/desktop/macos/autofill-extension/CredentialProviderViewController.swift index 5568b2e75db..ec4f1dcb543 100644 --- a/apps/desktop/macos/autofill-extension/CredentialProviderViewController.swift +++ b/apps/desktop/macos/autofill-extension/CredentialProviderViewController.swift @@ -11,63 +11,138 @@ import os class CredentialProviderViewController: ASCredentialProviderViewController { let logger: Logger - // There is something a bit strange about the initialization/deinitialization in this class. - // Sometimes deinit won't be called after a request has successfully finished, - // which would leave this class hanging in memory and the IPC connection open. - // - // If instead I make this a static, the deinit gets called correctly after each request. - // I think we still might want a static regardless, to be able to reuse the connection if possible. - let client: MacOsProviderClient = { - let logger = Logger(subsystem: "com.bitwarden.desktop.autofill-extension", category: "credential-provider") + @IBOutlet weak var statusLabel: NSTextField! + @IBOutlet weak var logoImageView: NSImageView! + + // The IPC client to communicate with the Bitwarden desktop app + private var client: MacOsProviderClient? + + // Timer for checking connection status + private var connectionMonitorTimer: Timer? + private var lastConnectionStatus: ConnectionStatus = .disconnected + + // We changed the getClient method to be async, here's why: + // This is so that we can check if the app is running, and launch it, without blocking the main thread + // Blocking the main thread caused MacOS layouting to 'fail' or at least be very delayed, which caused our getWindowPositioning code to sent 0,0. + // We also properly retry the IPC connection which sometimes would take some time to be up and running, depending on CPU load, phase of jupiters moon, etc. + private func getClient() async -> MacOsProviderClient { + if let client = self.client { + return client + } + let logger = Logger(subsystem: "com.bitwarden.desktop.autofill-extension", category: "credential-provider") + // Check if the Electron app is running let workspace = NSWorkspace.shared let isRunning = workspace.runningApplications.contains { app in app.bundleIdentifier == "com.bitwarden.desktop" } - + if !isRunning { - logger.log("[autofill-extension] Bitwarden Desktop not running, attempting to launch") - - // Try to launch the app + logger.log("[autofill-extension] Bitwarden Desktop not running, attempting to launch") + + // Launch the app and wait for it to be ready if let appURL = workspace.urlForApplication(withBundleIdentifier: "com.bitwarden.desktop") { - let semaphore = DispatchSemaphore(value: 0) - - workspace.openApplication(at: appURL, - configuration: NSWorkspace.OpenConfiguration()) { app, error in - if let error = error { - logger.error("[autofill-extension] Failed to launch Bitwarden Desktop: \(error.localizedDescription)") - } else if let app = app { - logger.log("[autofill-extension] Successfully launched Bitwarden Desktop") - } else { - logger.error("[autofill-extension] Failed to launch Bitwarden Desktop: unknown error") + await withCheckedContinuation { continuation in + workspace.openApplication(at: appURL, configuration: NSWorkspace.OpenConfiguration()) { app, error in + if let error = error { + logger.error("[autofill-extension] Failed to launch Bitwarden Desktop: \(error.localizedDescription)") + } else { + logger.log("[autofill-extension] Successfully launched Bitwarden Desktop") + } + continuation.resume() } - semaphore.signal() } - - // Wait for launch completion with timeout - _ = semaphore.wait(timeout: .now() + 5.0) - - // Add a small delay to allow for initialization - Thread.sleep(forTimeInterval: 1.0) - } else { - logger.error("[autofill-extension] Could not find Bitwarden Desktop app") } - } else { - logger.log("[autofill-extension] Bitwarden Desktop is running") + } + + logger.log("[autofill-extension] Connecting to Bitwarden over IPC") + + // Retry connecting to the Bitwarden IPC with an increasing delay + let maxRetries = 20 + let delayMs = 500 + var newClient: MacOsProviderClient? + + for attempt in 1...maxRetries { + logger.log("[autofill-extension] Connection attempt \(attempt)") + + // Create a new client instance for each retry + newClient = MacOsProviderClient.connect() + try? await Task.sleep(nanoseconds: UInt64(100 * attempt + (delayMs * 1_000_000))) // Convert ms to nanoseconds + let connectionStatus = newClient!.getConnectionStatus() + + logger.log("[autofill-extension] Connection attempt \(attempt), status: \(connectionStatus == .connected ? "connected" : "disconnected")") + + if connectionStatus == .connected { + logger.log("[autofill-extension] Successfully connected to Bitwarden (attempt \(attempt))") + break + } else { + if attempt < maxRetries { + logger.log("[autofill-extension] Retrying connection") + } else { + logger.error("[autofill-extension] Failed to connect after \(maxRetries) attempts, final status: \(connectionStatus == .connected ? "connected" : "disconnected")") + } + } } - logger.log("[autofill-extension] Connecting to Bitwarden over IPC") - - return MacOsProviderClient.connect() - }() + self.client = newClient + return newClient! + } + + // Setup the connection monitoring timer + private func setupConnectionMonitoring() { + // Check connection status every 1 second + connectionMonitorTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in + self?.checkConnectionStatus() + } + + // Make sure timer runs even when UI is busy + RunLoop.current.add(connectionMonitorTimer!, forMode: .common) + + // Initial check + checkConnectionStatus() + } + + // Check the connection status by calling into Rust + // If the connection is has changed and is now disconnected, cancel the request + private func checkConnectionStatus() { + // Only check connection status if the client has been initialized. + // Initialization is done asynchronously, so we might be called before it's ready + // In that case we just skip this check and wait for the next timer tick and re-check + guard let client = self.client else { + return + } + + // Get the current connection status from Rust + let currentStatus = client.getConnectionStatus() + + // Only post notification if state changed + if currentStatus != lastConnectionStatus { + if(currentStatus == .connected) { + logger.log("[autofill-extension] Connection status changed: Connected") + } else { + logger.log("[autofill-extension] Connection status changed: Disconnected") + } + + // Save the new status + lastConnectionStatus = currentStatus + + // If we just disconnected, try to cancel the request + if currentStatus == .disconnected { + self.extensionContext.cancelRequest(withError: BitwardenError.Internal("Bitwarden desktop app disconnected")) + } + } + } init() { logger = Logger(subsystem: "com.bitwarden.desktop.autofill-extension", category: "credential-provider") logger.log("[autofill-extension] initializing extension") - super.init(nibName: nil, bundle: nil) + super.init(nibName: "CredentialProviderViewController", bundle: nil) + + // Setup connection monitoring now that self is available + setupConnectionMonitoring() } required init?(coder: NSCoder) { @@ -76,45 +151,114 @@ class CredentialProviderViewController: ASCredentialProviderViewController { deinit { logger.log("[autofill-extension] deinitializing extension") - } - - - @IBAction func cancel(_ sender: AnyObject?) { - self.extensionContext.cancelRequest(withError: NSError(domain: ASExtensionErrorDomain, code: ASExtensionError.userCanceled.rawValue)) - } - - @IBAction func passwordSelected(_ sender: AnyObject?) { - let passwordCredential = ASPasswordCredential(user: "j_appleseed", password: "apple1234") - self.extensionContext.completeRequest(withSelectedCredential: passwordCredential, completionHandler: nil) - } - - private func getWindowPosition() -> Position { - let frame = self.view.window?.frame ?? .zero - let screenHeight = NSScreen.main?.frame.height ?? 0 - // frame.width and frame.height is always 0. Estimating works OK for now. - let estimatedWidth:CGFloat = 400; - let estimatedHeight:CGFloat = 200; - let centerX = Int32(round(frame.origin.x + estimatedWidth/2)) - let centerY = Int32(round(screenHeight - (frame.origin.y + estimatedHeight/2))) - - return Position(x: centerX, y:centerY) + // Stop the connection monitor timer + connectionMonitorTimer?.invalidate() + connectionMonitorTimer = nil } - override func loadView() { - let view = NSView() - // Hide the native window since we only need the IPC connection - view.isHidden = true - self.view = view + private func getWindowPosition() async -> Position { + let screenHeight = NSScreen.main?.frame.height ?? 1440 + + logger.log("[autofill-extension] position: Getting window position") + + // To whomever is reading this. Sorry. But MacOS couldn't give us an accurate window positioning, possibly due to animations + // So I added some retry logic, as well as a fall back to the mouse position which is likely at the sort of the right place. + // In my testing we often succed after 4-7 attempts. + // Wait for window frame to stabilize (animation to complete) + var lastFrame: CGRect = .zero + var stableCount = 0 + let requiredStableChecks = 3 + let maxAttempts = 20 + var attempts = 0 + + while stableCount < requiredStableChecks && attempts < maxAttempts { + let currentFrame: CGRect = self.view.window?.frame ?? .zero + + if currentFrame.equalTo(lastFrame) && !currentFrame.equalTo(.zero) { + stableCount += 1 + } else { + stableCount = 0 + lastFrame = currentFrame + } + + try? await Task.sleep(nanoseconds: 16_666_666) // ~60fps (16.67ms) + attempts += 1 + } + + let finalWindowFrame = self.view.window?.frame ?? .zero + logger.log("[autofill-extension] position: Final window frame: \(NSStringFromRect(finalWindowFrame))") + + // Use stabilized window frame if available, otherwise fallback to mouse position + let x, y: Int32 + if finalWindowFrame.origin.x != 0 || finalWindowFrame.origin.y != 0 { + let centerX = Int32(round(finalWindowFrame.origin.x)) + let centerY = Int32(round(screenHeight - finalWindowFrame.origin.y)) + logger.log("[autofill-extension] position: Using window position: x=\(centerX), y=\(centerY)") + x = centerX + y = centerY + } else { + // Fallback to mouse position + let mouseLocation = NSEvent.mouseLocation + let mouseX = Int32(round(mouseLocation.x)) + let mouseY = Int32(round(screenHeight - mouseLocation.y)) + logger.log("[autofill-extension] position: Using mouse position fallback: x=\(mouseX), y=\(mouseY)") + x = mouseX + y = mouseY + } + // Add 100 pixels to the x-coordinate to offset the native OS dialog positioning. + return Position(x: x + 100, y: y) } - + + override func viewDidLoad() { + super.viewDidLoad() + + // Initially hide the view + self.view.isHidden = true + } + + override func prepareInterfaceForExtensionConfiguration() { + // Show the configuration UI + self.view.isHidden = false + + // Set the localized message + statusLabel.stringValue = NSLocalizedString("autofillConfigurationMessage", comment: "Message shown when Bitwarden is enabled in system settings") + + // Send the native status request asynchronously + Task { + let client = await getClient() + client.sendNativeStatus(key: "request-sync", value: "") + } + + // Complete the configuration after 2 seconds + DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in + self?.extensionContext.completeExtensionConfigurationRequest() + } + } + + /* + In order to implement this method, we need to query the state of the vault to be unlocked and have one and only one matching credential so that it doesn't need to show ui. + If we do show UI, it's going to fail and disconnect after the platform timeout which is 3s. + For now we just claim to always need UI displayed. + */ override func provideCredentialWithoutUserInteraction(for credentialRequest: any ASCredentialRequest) { + let error = ASExtensionError(.userInteractionRequired) + self.extensionContext.cancelRequest(withError: error) + return + } + + /* + Implement this method if provideCredentialWithoutUserInteraction(for:) can fail with + ASExtensionError.userInteractionRequired. In this case, the system may present your extension's + UI and call this method. Show appropriate UI for authenticating the user then provide the password + by completing the extension request with the associated ASPasswordCredential. + */ + override func prepareInterfaceToProvideCredential(for credentialRequest: ASCredentialRequest) { let timeoutTimer = createTimer() - if let request = credentialRequest as? ASPasskeyCredentialRequest { if let passkeyIdentity = request.credentialIdentity as? ASPasskeyCredentialIdentity { - - logger.log("[autofill-extension] provideCredentialWithoutUserInteraction2(passkey) called \(request)") + + logger.log("[autofill-extension] prepareInterfaceToProvideCredential (passkey) called \(request)") class CallbackImpl: PreparePasskeyAssertionCallback { let ctx: ASCredentialProviderExtensionContext @@ -154,18 +298,25 @@ class CredentialProviderViewController: ASCredentialProviderViewController { UserVerification.discouraged } - let req = PasskeyAssertionWithoutUserInterfaceRequest( - rpId: passkeyIdentity.relyingPartyIdentifier, - credentialId: passkeyIdentity.credentialID, - userName: passkeyIdentity.userName, - userHandle: passkeyIdentity.userHandle, - recordIdentifier: passkeyIdentity.recordIdentifier, - clientDataHash: request.clientDataHash, - userVerification: userVerification, - windowXy: self.getWindowPosition() - ) - - self.client.preparePasskeyAssertionWithoutUserInterface(request: req, callback: CallbackImpl(self.extensionContext, self.logger, timeoutTimer)) + /* + We're still using the old request type here, because we're sending the same data, we're expecting a single credential to be used + */ + Task { + let windowPosition = await self.getWindowPosition() + let req = PasskeyAssertionWithoutUserInterfaceRequest( + rpId: passkeyIdentity.relyingPartyIdentifier, + credentialId: passkeyIdentity.credentialID, + userName: passkeyIdentity.userName, + userHandle: passkeyIdentity.userHandle, + recordIdentifier: passkeyIdentity.recordIdentifier, + clientDataHash: request.clientDataHash, + userVerification: userVerification, + windowXy: windowPosition + ) + + let client = await getClient() + client.preparePasskeyAssertionWithoutUserInterface(request: req, callback: CallbackImpl(self.extensionContext, self.logger, timeoutTimer)) + } return } } @@ -176,16 +327,6 @@ class CredentialProviderViewController: ASCredentialProviderViewController { self.extensionContext.cancelRequest(withError: BitwardenError.Internal("Invalid authentication request")) } - /* - Implement this method if provideCredentialWithoutUserInteraction(for:) can fail with - ASExtensionError.userInteractionRequired. In this case, the system may present your extension's - UI and call this method. Show appropriate UI for authenticating the user then provide the password - by completing the extension request with the associated ASPasswordCredential. - - override func prepareInterfaceToProvideCredential(for credentialIdentity: ASPasswordCredentialIdentity) { - } - */ - private func createTimer() -> DispatchWorkItem { // Create a timer for 600 second timeout let timeoutTimer = DispatchWorkItem { [weak self] in @@ -246,18 +387,32 @@ class CredentialProviderViewController: ASCredentialProviderViewController { UserVerification.discouraged } - let req = PasskeyRegistrationRequest( - rpId: passkeyIdentity.relyingPartyIdentifier, - userName: passkeyIdentity.userName, - userHandle: passkeyIdentity.userHandle, - clientDataHash: request.clientDataHash, - userVerification: userVerification, - supportedAlgorithms: request.supportedAlgorithms.map{ Int32($0.rawValue) }, - windowXy: self.getWindowPosition() - ) + // Convert excluded credentials to an array of credential IDs + var excludedCredentialIds: [Data] = [] + if #available(macOSApplicationExtension 15.0, *) { + if let excludedCreds = request.excludedCredentials { + excludedCredentialIds = excludedCreds.map { $0.credentialID } + } + } + logger.log("[autofill-extension] prepareInterface(passkey) calling preparePasskeyRegistration") - self.client.preparePasskeyRegistration(request: req, callback: CallbackImpl(self.extensionContext, self.logger, timeoutTimer)) + Task { + let windowPosition = await self.getWindowPosition() + let req = PasskeyRegistrationRequest( + rpId: passkeyIdentity.relyingPartyIdentifier, + userName: passkeyIdentity.userName, + userHandle: passkeyIdentity.userHandle, + clientDataHash: request.clientDataHash, + userVerification: userVerification, + supportedAlgorithms: request.supportedAlgorithms.map{ Int32($0.rawValue) }, + windowXy: windowPosition, + excludedCredentials: excludedCredentialIds + ) + + let client = await getClient() + client.preparePasskeyRegistration(request: req, callback: CallbackImpl(self.extensionContext, self.logger, timeoutTimer)) + } return } } @@ -310,18 +465,22 @@ class CredentialProviderViewController: ASCredentialProviderViewController { UserVerification.discouraged } - let req = PasskeyAssertionRequest( - rpId: requestParameters.relyingPartyIdentifier, - clientDataHash: requestParameters.clientDataHash, - userVerification: userVerification, - allowedCredentials: requestParameters.allowedCredentials, - windowXy: self.getWindowPosition() - //extensionInput: requestParameters.extensionInput, - ) - let timeoutTimer = createTimer() - self.client.preparePasskeyAssertion(request: req, callback: CallbackImpl(self.extensionContext, self.logger, timeoutTimer)) + Task { + let windowPosition = await self.getWindowPosition() + let req = PasskeyAssertionRequest( + rpId: requestParameters.relyingPartyIdentifier, + clientDataHash: requestParameters.clientDataHash, + userVerification: userVerification, + allowedCredentials: requestParameters.allowedCredentials, + windowXy: windowPosition + //extensionInput: requestParameters.extensionInput, // We don't support extensions yet + ) + + let client = await getClient() + client.preparePasskeyAssertion(request: req, callback: CallbackImpl(self.extensionContext, self.logger, timeoutTimer)) + } return } } diff --git a/apps/desktop/macos/autofill-extension/Info.plist b/apps/desktop/macos/autofill-extension/Info.plist index 539cfa35b9d..7de0d4d152b 100644 --- a/apps/desktop/macos/autofill-extension/Info.plist +++ b/apps/desktop/macos/autofill-extension/Info.plist @@ -10,9 +10,9 @@ ProvidesPasskeys + ShowsConfigurationUI + - ASCredentialProviderExtensionShowsConfigurationUI - NSExtensionPointIdentifier com.apple.authentication-services-credential-provider-ui diff --git a/apps/desktop/macos/autofill-extension/autofill_extension.entitlements b/apps/desktop/macos/autofill-extension/autofill_extension.entitlements index 86c7195768e..d5c7b8a2cc8 100644 --- a/apps/desktop/macos/autofill-extension/autofill_extension.entitlements +++ b/apps/desktop/macos/autofill-extension/autofill_extension.entitlements @@ -2,11 +2,9 @@ - com.apple.developer.authentication-services.autofill-credential-provider - - com.apple.security.app-sandbox - - com.apple.security.application-groups + com.apple.security.app-sandbox + + com.apple.security.application-groups LTZ2PFU5D6.com.bitwarden.desktop diff --git a/apps/desktop/macos/autofill-extension/bitwarden-icon.png b/apps/desktop/macos/autofill-extension/bitwarden-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..9a05bc7bbdd8061e741cbfdbcbc7148366f3ad61 GIT binary patch literal 3291 zcmV<13?%c3P)|~|L-n`m1W7rbaV|hwUR~~dlUN8$qJiFrO+Ci>VOCTs|UdD5G?{`J57Prm%ko`HD=KKJEs{E8=T^y8ZcJ*DL1t*sT?RE8{? z+srLt2!oAsX$U5w4TfCGg*6RwVUM1+zx>XB@+JS!Co!MI^Z&$8e!+b`@IUbaA7=#D4Ue9l_~_Ta;|IR{r#+36r?=;L;6Ks} z2$|?W6poQ3Ar}(Dfh0;YsgUg$DQ%6A$%K#%Yl#jzwzZ^=NgSJFq2Ty@87-0 zcYpso+O}e&C~ZbAoPGHHzvmtQ>i56S9h_WYXJ=o5Dui(0aLeKI9y{yLW^|^OSPocHF>l%&*FYg6Q}n z47ts@JKN6AKVOG14YHn9$0 zk7w$|U+{bn+<%XcH^+1`&4pYlO*1+>`+N+!&AF>Rz_B48GmXjNIE1+i-}H*taXNF$ zkeOV_49VdK|Jqmj>Mwi9ueE5Nlv}2`G&&%6aPDa(%*TY4$!6}>`Td+dM+X~BOSur{ z(jjMVSI4r(U~b8prr0qIxy`vNY%NlYT$m{tQo`JYLZ^(@hKw;*E;MFyy9oxxMlQ54 zzbbcd?h18;F*MfD&|#Y~cWJ|p6(X?_=F(=4D4$^HkW(D1xv)_fj+?G>?n=$2+>+za z>106%7UpiGN^zP69av>hP?+0P(YQHJ+9;PQPa1NYb60B;6uY1fSu1Gn){b#Fou))% zaf~6i9NTLBc62cWcrTsQK28!fWgafGulccE%0t7Bvvg}J3wPBM3}R%KI%ZJsi>w1pwJId`STf!V0gJZUn= z+_gp!R)-54WhGjYI|;`$sE#pDYBL>kg>zR5DVK)iLd{@)9i%drkEx)|3PL_n2#e-Y zVOU{>+`+jkbYy2#NCsgOQhptTin$c#mR57A$S24e%P|w%qFCmbp@VLE@fSSb?cVmT$EQ@y zF+@&lLmldX+`-8eP8uPX22pM~w#_4Ne$?H#c^plM4jUXQM29V3{X1UZ`S;)B<2~}` zM{Or0A$8E94mpt1T=-fok)L{J?!v|fsUn2Kg&e;14}Ol9e(l3<_dWmS zmoQ0{4x~gXlPy;{xxz`?TBV|pEh@sPN8a-IUi-+qe7cf4kZF}Ir+Ft*b4|(OQ ze$J<(Bb7Q3)f{{Hq5J&sE56FZFMO`s{jDE(eQ*1f8`?~xZMo%uw$$O4Aa`(bg(IaV zbr_U7=s<{K=l#te_=R5k$UA-NYJzguj=lJ|JkJlk;;TIT!soi(PdxHYulyHp*x}5O z10j?P-CSiZgk0t13a1_8SPqt?4#oz@lnY_!_w7&pjsMnL-}M2XnwA66;m>}<7xbQe&`e@I;JRO z4pkP5MF&EVJ2<(sI-Na1$QGj1LE#u7QP}BhZ+Xv+ebZn0F^|0YS3DyfzUz;D@&5BG zU$U?HvWMKs>)-S%zV16-<1N2(lhfJiKsFLm+L{YRA&TRpZ^zuh$rVmFZ#+&&B?m%C z6(Ms>2jX<*E$_YICExKH-}~yH_sRV9-}?sN^)0{M1NYzKPQLHekNCRpc#X$Cd}e27 zstBpWC?bju$%Q0Q??vw5+?{ni@%SS z^JTxw^Y6dUojm+mpW#j(``|~s@>M_UdtdWQI=dF9Nn0zIHY!-Oxg{(^Nl(1R6;7_u z``-8ygb=c|3Ly&FLP!@J+v(&uJ*V&akvI9eZ~tL${pH6!Q?GsfJG|uEf7tiF=6`c` zAKMI$5e^)bt!>#_MIwZ3?RfkxuSM=)uJ#$f=^MZQbvwK7OI?^tB~RL{7;+&q(PqNp zxM9afyz~#f$alW%D}DZNex5sd?1LZixBmH0`@Vnsi#ofHotJH72IbO*h-k1)hc=7G zI&QqZ|Mcg-?0xTh-(&9J+|@pGJn?}aJv+PiOQEzGwoz1=Te3|RO=DEHGso##ulg@< z_u4nSYcG4r7y8bZ{ccZr?1LZieXoAK?|Jnv^w@{3v*+09jBJ8cmtkG=1GA9RIzdY}25zUlj4?{xk-Gs(v+noGl)RPNi)!yLOer_*4jVhkB_VaV-r z&-+DG2$wQqR0j~wTm?qMfmgk0F>NsSE= zZJyNHOxl{Q;e&7ZXWxADJ#YL49IkNY>Gje7`#;{|-sk?}Jr91-AFPhy_A=im#U_ch=3$M1RQxBY2n_kK1jO!K7DHZ;G+qWLuz z&7}pE&3p>dv5pVkeE-tM{ovntyZ-r@W4IqfB*aM#XacSwQD}!_3PJ% zJn7oCYp!3v4nywX+O=!0U%&3!wQH_lzwW}dYu7yG`t|E@6CcG5T*nj0v!3;=XFcng Z`+p}j2wIZUE=m9Z002ovPDHLkV1iQWv4Q{q literal 0 HcmV?d00001 diff --git a/apps/desktop/macos/autofill-extension/en.lproj/Localizable.strings b/apps/desktop/macos/autofill-extension/en.lproj/Localizable.strings new file mode 100644 index 00000000000..95730dff286 --- /dev/null +++ b/apps/desktop/macos/autofill-extension/en.lproj/Localizable.strings @@ -0,0 +1,2 @@ +/* Message shown during passkey configuration */ +"autofillConfigurationMessage" = "Enabling Bitwarden..."; diff --git a/apps/desktop/macos/desktop.xcodeproj/project.pbxproj b/apps/desktop/macos/desktop.xcodeproj/project.pbxproj index ff257097f26..ed19fc9ef5d 100644 --- a/apps/desktop/macos/desktop.xcodeproj/project.pbxproj +++ b/apps/desktop/macos/desktop.xcodeproj/project.pbxproj @@ -9,6 +9,8 @@ /* Begin PBXBuildFile section */ 3368DB392C654B8100896B75 /* BitwardenMacosProviderFFI.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3368DB382C654B8100896B75 /* BitwardenMacosProviderFFI.xcframework */; }; 3368DB3B2C654F3800896B75 /* BitwardenMacosProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3368DB3A2C654F3800896B75 /* BitwardenMacosProvider.swift */; }; + 9AE299092DF9D82E00AAE454 /* bitwarden-icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 9AE299082DF9D82E00AAE454 /* bitwarden-icon.png */; }; + 9AE299122DFB57A200AAE454 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 9AE2990D2DFB57A200AAE454 /* Localizable.strings */; }; E1DF713F2B342F6900F29026 /* AuthenticationServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E1DF713E2B342F6900F29026 /* AuthenticationServices.framework */; }; E1DF71422B342F6900F29026 /* CredentialProviderViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1DF71412B342F6900F29026 /* CredentialProviderViewController.swift */; }; E1DF71452B342F6900F29026 /* CredentialProviderViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = E1DF71432B342F6900F29026 /* CredentialProviderViewController.xib */; }; @@ -18,6 +20,8 @@ 3368DB382C654B8100896B75 /* BitwardenMacosProviderFFI.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = BitwardenMacosProviderFFI.xcframework; path = ../desktop_native/macos_provider/BitwardenMacosProviderFFI.xcframework; sourceTree = ""; }; 3368DB3A2C654F3800896B75 /* BitwardenMacosProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BitwardenMacosProvider.swift; sourceTree = ""; }; 968ED08A2C52A47200FFFEE6 /* ReleaseAppStore.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ReleaseAppStore.xcconfig; sourceTree = ""; }; + 9AE299082DF9D82E00AAE454 /* bitwarden-icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "bitwarden-icon.png"; sourceTree = ""; }; + 9AE2990C2DFB57A200AAE454 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = Localizable.strings; sourceTree = ""; }; D83832AB2D67B9AE003FB9F8 /* Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; D83832AD2D67B9D0003FB9F8 /* ReleaseDeveloper.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = ReleaseDeveloper.xcconfig; sourceTree = ""; }; E1DF713C2B342F6900F29026 /* autofill-extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "autofill-extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -41,6 +45,14 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 9AE2990E2DFB57A200AAE454 /* en.lproj */ = { + isa = PBXGroup; + children = ( + 9AE2990D2DFB57A200AAE454 /* Localizable.strings */, + ); + path = en.lproj; + sourceTree = ""; + }; E1DF711D2B342E2800F29026 = { isa = PBXGroup; children = ( @@ -73,6 +85,8 @@ E1DF71402B342F6900F29026 /* autofill-extension */ = { isa = PBXGroup; children = ( + 9AE2990E2DFB57A200AAE454 /* en.lproj */, + 9AE299082DF9D82E00AAE454 /* bitwarden-icon.png */, 3368DB3A2C654F3800896B75 /* BitwardenMacosProvider.swift */, E1DF71412B342F6900F29026 /* CredentialProviderViewController.swift */, E1DF71432B342F6900F29026 /* CredentialProviderViewController.xib */, @@ -124,6 +138,7 @@ knownRegions = ( en, Base, + sv, ); mainGroup = E1DF711D2B342E2800F29026; productRefGroup = E1DF71272B342E2800F29026 /* Products */; @@ -141,6 +156,8 @@ buildActionMask = 2147483647; files = ( E1DF71452B342F6900F29026 /* CredentialProviderViewController.xib in Resources */, + 9AE299122DFB57A200AAE454 /* Localizable.strings in Resources */, + 9AE299092DF9D82E00AAE454 /* bitwarden-icon.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -159,6 +176,14 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ + 9AE2990D2DFB57A200AAE454 /* Localizable.strings */ = { + isa = PBXVariantGroup; + children = ( + 9AE2990C2DFB57A200AAE454 /* en */, + ); + name = Localizable.strings; + sourceTree = ""; + }; E1DF71432B342F6900F29026 /* CredentialProviderViewController.xib */ = { isa = PBXVariantGroup; children = ( diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 19ab9e783d4..6dc92035169 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -18,6 +18,7 @@ "scripts": { "postinstall": "electron-rebuild", "start": "cross-env ELECTRON_IS_DEV=0 ELECTRON_NO_UPDATER=1 electron ./build", + "build-native-macos": "cd desktop_native && ./macos_provider/build.sh && node build.js cross-platform", "build-native": "cd desktop_native && node build.js", "build": "concurrently -n Main,Rend,Prel -c yellow,cyan \"npm run build:main\" \"npm run build:renderer\" \"npm run build:preload\"", "build:dev": "concurrently -n Main,Rend,Prel -c yellow,cyan \"npm run build:main:dev\" \"npm run build:renderer:dev\" \"npm run build:preload:dev\"", @@ -28,7 +29,7 @@ "build:macos-extension:mas": "./desktop_native/macos_provider/build.sh && node scripts/build-macos-extension.js mas", "build:macos-extension:masdev": "./desktop_native/macos_provider/build.sh && node scripts/build-macos-extension.js mas-dev", "build:main": "cross-env NODE_ENV=production webpack --config webpack.config.js --config-name main", - "build:main:dev": "npm run build-native && cross-env NODE_ENV=development webpack --config webpack.config.js --config-name main", + "build:main:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js --config-name main", "build:main:watch": "npm run build-native && cross-env NODE_ENV=development webpack --config webpack.config.js --config-name main --watch", "build:renderer": "cross-env NODE_ENV=production webpack --config webpack.config.js --config-name renderer", "build:renderer:dev": "cross-env NODE_ENV=development webpack --config webpack.config.js --config-name renderer", @@ -41,25 +42,21 @@ "pack:lin:flatpak": "flatpak-builder --repo=../../.flatpak-repo ../../.flatpak ./resources/com.bitwarden.desktop.devel.yaml --install-deps-from=flathub --force-clean && flatpak build-bundle ../../.flatpak-repo/ ./dist/com.bitwarden.desktop.flatpak com.bitwarden.desktop", "pack:lin": "npm run clean:dist && electron-builder --linux --x64 -p never && export SNAP_FILE=$(realpath ./dist/bitwarden_*.snap) && unsquashfs -d ./dist/tmp-snap/ $SNAP_FILE && mkdir -p ./dist/tmp-snap/meta/polkit/ && cp ./resources/com.bitwarden.desktop.policy ./dist/tmp-snap/meta/polkit/polkit.com.bitwarden.desktop.policy && rm $SNAP_FILE && snap pack --compression=lzo ./dist/tmp-snap/ && mv ./*.snap ./dist/ && rm -rf ./dist/tmp-snap/", "pack:lin:arm64": "npm run clean:dist && electron-builder --dir -p never && tar -czvf ./dist/bitwarden_desktop_arm64.tar.gz -C ./dist/linux-arm64-unpacked/ .", - "pack:mac": "npm run clean:dist && electron-builder --mac --universal -p never", - "pack:mac:with-extension": "npm run clean:dist && npm run build:macos-extension:mac && electron-builder --mac --universal -p never", + "pack:mac": "npm run clean:dist && npm run build:macos-extension:mac && electron-builder --mac --universal -p never", "pack:mac:arm64": "npm run clean:dist && electron-builder --mac --arm64 -p never", - "pack:mac:mas": "npm run clean:dist && electron-builder --mac mas --universal -p never", - "pack:mac:mas:with-extension": "npm run clean:dist && npm run build:macos-extension:mas && electron-builder --mac mas --universal -p never", - "pack:mac:masdev": "npm run clean:dist && electron-builder --mac mas-dev --universal -p never", - "pack:mac:masdev:with-extension": "npm run clean:dist && npm run build:macos-extension:masdev && electron-builder --mac mas-dev --universal -p never", + "pack:mac:mas": "npm run clean:dist && npm run build:macos-extension:mas && electron-builder --mac mas --universal -p never", + "pack:mac:masdev": "npm run clean:dist && npm run build:macos-extension:masdev && electron-builder --mac mas-dev --universal -p never", + "pack:local:mac": "npm run clean:dist && npm run build:macos-extension:masdev && electron-builder --mac mas-dev --universal -p never -c.mac.provisioningProfile=\"\" -c.mas.provisioningProfile=\"\"", "pack:win": "npm run clean:dist && electron-builder --win --x64 --arm64 --ia32 -p never -c.win.signtoolOptions.certificateSubjectName=\"8bit Solutions LLC\"", + "pack:win:arm64": "npm run clean:dist && electron-builder --win --arm64 -p never -c.win.signtoolOptions.certificateSubjectName=\"8bit Solutions LLC\"", "pack:win:beta": "npm run clean:dist && electron-builder --config electron-builder.beta.json --win --x64 --arm64 --ia32 -p never -c.win.signtoolOptions.certificateSubjectName=\"8bit Solutions LLC\"", "pack:win:ci": "npm run clean:dist && electron-builder --win --x64 --arm64 --ia32 -p never", "dist:dir": "npm run build && npm run pack:dir", "dist:lin": "npm run build && npm run pack:lin", "dist:lin:arm64": "npm run build && npm run pack:lin:arm64", "dist:mac": "npm run build && npm run pack:mac", - "dist:mac:with-extension": "npm run build && npm run pack:mac:with-extension", "dist:mac:mas": "npm run build && npm run pack:mac:mas", - "dist:mac:mas:with-extension": "npm run build && npm run pack:mac:mas:with-extension", - "dist:mac:masdev": "npm run build:dev && npm run pack:mac:masdev", - "dist:mac:masdev:with-extension": "npm run build:dev && npm run pack:mac:masdev:with-extension", + "dist:mac:masdev": "npm run build && npm run pack:mac:masdev", "dist:win": "npm run build && npm run pack:win", "dist:win:ci": "npm run build && npm run pack:win:ci", "publish:lin": "npm run build && npm run clean:dist && electron-builder --linux --x64 -p always", @@ -70,6 +67,7 @@ "upload:mas": "xcrun altool --upload-app --type osx --file \"$(find ./dist/mas-universal/Bitwarden*.pkg)\" --apiKey $APP_STORE_CONNECT_AUTH_KEY --apiIssuer $APP_STORE_CONNECT_TEAM_ISSUER", "test": "jest", "test:watch": "jest --watch", - "test:watch:all": "jest --watchAll" + "test:watch:all": "jest --watchAll", + "local:win": "cd desktop_native/napi && npm run build && cd ../.. && npm run build:dev && npm run pack:win" } } diff --git a/apps/desktop/resources/entitlements.mac.plist b/apps/desktop/resources/entitlements.mac.plist index fe49256d71c..7763b84624d 100644 --- a/apps/desktop/resources/entitlements.mac.plist +++ b/apps/desktop/resources/entitlements.mac.plist @@ -6,8 +6,6 @@ LTZ2PFU5D6.com.bitwarden.desktop com.apple.developer.team-identifier LTZ2PFU5D6 - com.apple.developer.authentication-services.autofill-credential-provider - com.apple.security.cs.allow-jit diff --git a/apps/desktop/resources/entitlements.mas.inherit.plist b/apps/desktop/resources/entitlements.mas.inherit.plist index fca5f02d52d..7194d9409fc 100644 --- a/apps/desktop/resources/entitlements.mas.inherit.plist +++ b/apps/desktop/resources/entitlements.mas.inherit.plist @@ -4,9 +4,9 @@ com.apple.security.app-sandbox - com.apple.security.inherit - com.apple.security.cs.allow-jit + com.apple.security.inherit + diff --git a/apps/desktop/resources/entitlements.mas.plist b/apps/desktop/resources/entitlements.mas.plist index 3ebd56f0fd7..6d6d37d643e 100644 --- a/apps/desktop/resources/entitlements.mas.plist +++ b/apps/desktop/resources/entitlements.mas.plist @@ -6,19 +6,19 @@ LTZ2PFU5D6.com.bitwarden.desktop com.apple.developer.team-identifier LTZ2PFU5D6 - com.apple.developer.authentication-services.autofill-credential-provider - com.apple.security.app-sandbox com.apple.security.application-groups LTZ2PFU5D6.com.bitwarden.desktop - com.apple.security.network.client + com.apple.security.cs.allow-jit + + com.apple.security.device.usb com.apple.security.files.user-selected.read-write - com.apple.security.device.usb + com.apple.security.network.client com.apple.security.temporary-exception.files.home-relative-path.read-write @@ -32,10 +32,8 @@ /Library/Application Support/Microsoft Edge Beta/NativeMessagingHosts/ /Library/Application Support/Microsoft Edge Dev/NativeMessagingHosts/ /Library/Application Support/Microsoft Edge Canary/NativeMessagingHosts/ - /Library/Application Support/Vivaldi/NativeMessagingHosts/ + /Library/Application Support/Vivaldi/NativeMessagingHosts/ /Library/Application Support/Zen/NativeMessagingHosts/ - com.apple.security.cs.allow-jit - diff --git a/apps/desktop/sign.js b/apps/desktop/sign.js index 6a42666c46f..9ad66567711 100644 --- a/apps/desktop/sign.js +++ b/apps/desktop/sign.js @@ -1,8 +1,46 @@ /* eslint-disable @typescript-eslint/no-require-imports, no-console */ exports.default = async function (configuration) { - if (parseInt(process.env.ELECTRON_BUILDER_SIGN) === 1 && configuration.path.slice(-4) == ".exe") { + if ( + parseInt(process.env.ELECTRON_BUILDER_SIGN) === 1 && + (configuration.path.endsWith(".exe") || + configuration.path.endsWith(".appx") || + configuration.path.endsWith(".msix")) + ) { console.log(`[*] Signing file: ${configuration.path}`); + + // If signing APPX/MSIX, inspect the manifest Publisher before signing + if (configuration.path.endsWith(".appx") || configuration.path.endsWith(".msix")) { + try { + const path = require("path"); + const fs = require("fs"); + + // Extract architecture from filename (e.g., "Bitwarden-2025.10.2-x64.appx" -> "x64") + const filename = path.basename(configuration.path); + const archMatch = filename.match(/-(x64|arm64|ia32)\.(appx|msix)$/); + + if (archMatch) { + const arch = archMatch[1]; + const distDir = path.dirname(configuration.path); + const manifestPath = path.join(distDir, `__appx-${arch}`, "AppxManifest.xml"); + + if (fs.existsSync(manifestPath)) { + const manifestContent = fs.readFileSync(manifestPath, "utf8"); + + // Extract and display the Publisher line + const publisherMatch = manifestContent.match(/Publisher='([^']+)'/); + if (publisherMatch) { + console.log(`[*] APPX Manifest Publisher: ${publisherMatch[1]}`); + } + } else { + console.log(`[!] Manifest not found at: ${manifestPath}`); + } + } + } catch (error) { + console.log(`[!] Failed to read manifest: ${error.message}`); + } + } + require("child_process").execSync( `azuresigntool sign -v ` + `-kvu ${process.env.SIGNING_VAULT_URL} ` + @@ -18,5 +56,20 @@ exports.default = async function (configuration) { stdio: "inherit", }, ); + } else if (process.env.ELECTRON_BUILDER_SIGN_CERT) { + const certFile = process.env.ELECTRON_BUILDER_SIGN_CERT; + const certPw = process.env.ELECTRON_BUILDER_SIGN_CERT_PW; + console.log(`[*] Signing file: ${configuration.path} with ${certFile}`); + require("child_process").execSync( + "signtool.exe sign" + + " /fd SHA256" + + " /a" + + ` /f "${certFile}"` + + ` /p "${certPw}"` + + ` "${configuration.path}"`, + { + stdio: "inherit", + }, + ); } }; diff --git a/apps/desktop/sign.ps1 b/apps/desktop/sign.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..7709b3be8f3783970d353b93f862be63c64dca70 GIT binary patch literal 166 zcmZXMOA5kJ5Cm%-@D8~^-osz^x^f>c5RD0fpNA35>0^rEP6nEpp056m6<0bQ9C6KQF5Dh}*ev8D8i)U&qgS>{gQB=hFu=OuBmFOZ~%IhoX@{F;qhW41RP+5b_6 NL}@D6l$?PD857z^95(;} literal 0 HcmV?d00001 diff --git a/apps/desktop/src/app/app-routing.module.ts b/apps/desktop/src/app/app-routing.module.ts index b6e86ba19ff..ce84ca54bdb 100644 --- a/apps/desktop/src/app/app-routing.module.ts +++ b/apps/desktop/src/app/app-routing.module.ts @@ -43,10 +43,13 @@ import { AnonLayoutWrapperComponent, AnonLayoutWrapperData } from "@bitwarden/co import { LockComponent, ConfirmKeyConnectorDomainComponent } from "@bitwarden/key-management-ui"; import { maxAccountsGuardFn } from "../auth/guards/max-accounts.guard"; +import { reactiveUnlockVaultGuard } from "../autofill/guards/reactive-vault-guard"; +import { Fido2CreateComponent } from "../autofill/modal/credentials/fido2-create.component"; +import { Fido2ExcludedCiphersComponent } from "../autofill/modal/credentials/fido2-excluded-ciphers.component"; +import { Fido2VaultComponent } from "../autofill/modal/credentials/fido2-vault.component"; import { RemovePasswordComponent } from "../key-management/key-connector/remove-password.component"; import { VaultV2Component } from "../vault/app/vault/vault-v2.component"; -import { Fido2PlaceholderComponent } from "./components/fido2placeholder.component"; import { SendComponent } from "./tools/send/send.component"; /** @@ -112,12 +115,16 @@ const routes: Routes = [ canActivate: [authGuard], }, { - path: "passkeys", - component: Fido2PlaceholderComponent, + path: "fido2-assertion", + component: Fido2VaultComponent, }, { - path: "passkeys", - component: Fido2PlaceholderComponent, + path: "fido2-creation", + component: Fido2CreateComponent, + }, + { + path: "fido2-excluded", + component: Fido2ExcludedCiphersComponent, }, { path: "", @@ -263,7 +270,7 @@ const routes: Routes = [ }, { path: "lock", - canActivate: [lockGuard()], + canActivate: [lockGuard(), reactiveUnlockVaultGuard], data: { pageIcon: LockIcon, pageTitle: { diff --git a/apps/desktop/src/app/app.component.ts b/apps/desktop/src/app/app.component.ts index 4b6dcab0dff..30ef27f7df9 100644 --- a/apps/desktop/src/app/app.component.ts +++ b/apps/desktop/src/app/app.component.ts @@ -103,7 +103,7 @@ const SyncInterval = 6 * 60 * 60 * 1000; // 6 hours - +
@@ -140,6 +140,7 @@ export class AppComponent implements OnInit, OnDestroy { @ViewChild("loginApproval", { read: ViewContainerRef, static: true }) loginApprovalModalRef: ViewContainerRef; + showHeader$ = this.accountService.showHeader$; loading = false; private lastActivity: Date = null; diff --git a/apps/desktop/src/app/components/fido2placeholder.component.ts b/apps/desktop/src/app/components/fido2placeholder.component.ts deleted file mode 100644 index f1f52dae439..00000000000 --- a/apps/desktop/src/app/components/fido2placeholder.component.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { CommonModule } from "@angular/common"; -import { Component, OnDestroy, OnInit } from "@angular/core"; -import { Router } from "@angular/router"; -import { BehaviorSubject, Observable } from "rxjs"; - -import { - DesktopFido2UserInterfaceService, - DesktopFido2UserInterfaceSession, -} from "../../autofill/services/desktop-fido2-user-interface.service"; -import { DesktopSettingsService } from "../../platform/services/desktop-settings.service"; - -// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush -// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection -@Component({ - standalone: true, - imports: [CommonModule], - template: ` -
-

Select your passkey

- -
- -
- -
- - -
- `, -}) -export class Fido2PlaceholderComponent implements OnInit, OnDestroy { - session?: DesktopFido2UserInterfaceSession = null; - private cipherIdsSubject = new BehaviorSubject([]); - cipherIds$: Observable; - - constructor( - private readonly desktopSettingsService: DesktopSettingsService, - private readonly fido2UserInterfaceService: DesktopFido2UserInterfaceService, - private readonly router: Router, - ) {} - - ngOnInit() { - this.session = this.fido2UserInterfaceService.getCurrentSession(); - this.cipherIds$ = this.session?.availableCipherIds$; - } - - async chooseCipher(cipherId: string) { - // For now: Set UV to true - this.session?.confirmChosenCipher(cipherId, true); - - await this.router.navigate(["/"]); - await this.desktopSettingsService.setModalMode(false); - } - - ngOnDestroy() { - this.cipherIdsSubject.complete(); // Clean up the BehaviorSubject - } - - async confirmPasskey() { - try { - // Retrieve the current UI session to control the flow - if (!this.session) { - // todo: handle error - throw new Error("No session found"); - } - - // If we want to we could submit information to the session in order to create the credential - // const cipher = await session.createCredential({ - // userHandle: "userHandle2", - // userName: "username2", - // credentialName: "zxsd2", - // rpId: "webauthn.io", - // userVerification: true, - // }); - - this.session.notifyConfirmNewCredential(true); - - // Not sure this clean up should happen here or in session. - // The session currently toggles modal on and send us here - // But if this route is somehow opened outside of session we want to make sure we clean up? - await this.router.navigate(["/"]); - await this.desktopSettingsService.setModalMode(false); - } catch { - // TODO: Handle error appropriately - } - } - - async closeModal() { - await this.router.navigate(["/"]); - await this.desktopSettingsService.setModalMode(false); - - this.session.notifyConfirmNewCredential(false); - // little bit hacky: - this.session.confirmChosenCipher(null); - } -} diff --git a/apps/desktop/src/app/services/services.module.ts b/apps/desktop/src/app/services/services.module.ts index a0ee33a459c..d6f29b122ea 100644 --- a/apps/desktop/src/app/services/services.module.ts +++ b/apps/desktop/src/app/services/services.module.ts @@ -336,6 +336,7 @@ const safeProviders: SafeProvider[] = [ ConfigService, Fido2AuthenticatorServiceAbstraction, AccountService, + AuthService, ], }), safeProvider({ diff --git a/apps/desktop/src/autofill/guards/reactive-vault-guard.ts b/apps/desktop/src/autofill/guards/reactive-vault-guard.ts new file mode 100644 index 00000000000..d16787ef46a --- /dev/null +++ b/apps/desktop/src/autofill/guards/reactive-vault-guard.ts @@ -0,0 +1,42 @@ +import { inject } from "@angular/core"; +import { CanActivateFn, Router } from "@angular/router"; +import { combineLatest, map, switchMap, distinctUntilChanged } from "rxjs"; + +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; +import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; + +import { DesktopSettingsService } from "../../platform/services/desktop-settings.service"; + +/** + * Reactive route guard that redirects to the unlocked vault. + * Redirects to vault when unlocked in main window. + */ +export const reactiveUnlockVaultGuard: CanActivateFn = () => { + const router = inject(Router); + const authService = inject(AuthService); + const accountService = inject(AccountService); + const desktopSettingsService = inject(DesktopSettingsService); + + return combineLatest([accountService.activeAccount$, desktopSettingsService.modalMode$]).pipe( + switchMap(([account, modalMode]) => { + if (!account) { + return [true]; + } + + // Monitor when the vault has been unlocked. + return authService.authStatusFor$(account.id).pipe( + distinctUntilChanged(), + map((authStatus) => { + // If vault is unlocked and we're not in modal mode, redirect to vault + if (authStatus === AuthenticationStatus.Unlocked && !modalMode?.isModalModeActive) { + return router.createUrlTree(["/vault"]); + } + + // Otherwise keep user on the lock screen + return true; + }), + ); + }), + ); +}; diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-create.component.html b/apps/desktop/src/autofill/modal/credentials/fido2-create.component.html new file mode 100644 index 00000000000..67fc76aa317 --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-create.component.html @@ -0,0 +1,66 @@ +
+ + +
+ + +

+ {{ "savePasskeyQuestion" | i18n }} +

+
+ + +
+
+ + +
+
+ +
+ {{ "noMatchingLoginsForSite" | i18n }} +
+ +
+
+ + + + {{ c.subTitle }} + {{ "save" | i18n }} + + + + + + +
+
diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-create.component.spec.ts b/apps/desktop/src/autofill/modal/credentials/fido2-create.component.spec.ts new file mode 100644 index 00000000000..778215895ee --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-create.component.spec.ts @@ -0,0 +1,238 @@ +import { TestBed } from "@angular/core/testing"; +import { Router } from "@angular/router"; +import { mock, MockProxy } from "jest-mock-extended"; +import { BehaviorSubject, of } from "rxjs"; + +import { AccountService, Account } from "@bitwarden/common/auth/abstractions/account.service"; +import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service"; +import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { UserId } from "@bitwarden/common/types/guid"; +import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums"; +import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { DialogService } from "@bitwarden/components"; +import { PasswordRepromptService } from "@bitwarden/vault"; + +import { DesktopAutofillService } from "../../../autofill/services/desktop-autofill.service"; +import { DesktopSettingsService } from "../../../platform/services/desktop-settings.service"; +import { + DesktopFido2UserInterfaceService, + DesktopFido2UserInterfaceSession, +} from "../../services/desktop-fido2-user-interface.service"; + +import { Fido2CreateComponent } from "./fido2-create.component"; + +describe("Fido2CreateComponent", () => { + let component: Fido2CreateComponent; + let mockDesktopSettingsService: MockProxy; + let mockFido2UserInterfaceService: MockProxy; + let mockAccountService: MockProxy; + let mockCipherService: MockProxy; + let mockDesktopAutofillService: MockProxy; + let mockDialogService: MockProxy; + let mockDomainSettingsService: MockProxy; + let mockLogService: MockProxy; + let mockPasswordRepromptService: MockProxy; + let mockRouter: MockProxy; + let mockSession: MockProxy; + let mockI18nService: MockProxy; + + const activeAccountSubject = new BehaviorSubject({ + id: "test-user-id" as UserId, + email: "test@example.com", + emailVerified: true, + name: "Test User", + }); + + beforeEach(async () => { + mockDesktopSettingsService = mock(); + mockFido2UserInterfaceService = mock(); + mockAccountService = mock(); + mockCipherService = mock(); + mockDesktopAutofillService = mock(); + mockDialogService = mock(); + mockDomainSettingsService = mock(); + mockLogService = mock(); + mockPasswordRepromptService = mock(); + mockRouter = mock(); + mockSession = mock(); + mockI18nService = mock(); + + mockFido2UserInterfaceService.getCurrentSession.mockReturnValue(mockSession); + mockAccountService.activeAccount$ = activeAccountSubject; + + await TestBed.configureTestingModule({ + providers: [ + Fido2CreateComponent, + { provide: DesktopSettingsService, useValue: mockDesktopSettingsService }, + { provide: DesktopFido2UserInterfaceService, useValue: mockFido2UserInterfaceService }, + { provide: AccountService, useValue: mockAccountService }, + { provide: CipherService, useValue: mockCipherService }, + { provide: DesktopAutofillService, useValue: mockDesktopAutofillService }, + { provide: DialogService, useValue: mockDialogService }, + { provide: DomainSettingsService, useValue: mockDomainSettingsService }, + { provide: LogService, useValue: mockLogService }, + { provide: PasswordRepromptService, useValue: mockPasswordRepromptService }, + { provide: Router, useValue: mockRouter }, + { provide: I18nService, useValue: mockI18nService }, + ], + }).compileComponents(); + + component = TestBed.inject(Fido2CreateComponent); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + function createMockCiphers(): CipherView[] { + const cipher1 = new CipherView(); + cipher1.id = "cipher-1"; + cipher1.name = "Test Cipher 1"; + cipher1.type = CipherType.Login; + cipher1.login = { + username: "test1@example.com", + uris: [{ uri: "https://example.com", match: null }], + matchesUri: jest.fn().mockReturnValue(true), + get hasFido2Credentials() { + return false; + }, + } as any; + cipher1.reprompt = CipherRepromptType.None; + cipher1.deletedDate = null; + + return [cipher1]; + } + + describe("ngOnInit", () => { + beforeEach(() => { + mockSession.getRpId.mockResolvedValue("example.com"); + Object.defineProperty(mockDesktopAutofillService, "lastRegistrationRequest", { + get: jest.fn().mockReturnValue({ + userHandle: new Uint8Array([1, 2, 3]), + }), + configurable: true, + }); + mockDomainSettingsService.getUrlEquivalentDomains.mockReturnValue(of(new Set())); + }); + + it("should initialize session and set show header to false", async () => { + const mockCiphers = createMockCiphers(); + mockCipherService.getAllDecrypted.mockResolvedValue(mockCiphers); + + await component.ngOnInit(); + + expect(mockFido2UserInterfaceService.getCurrentSession).toHaveBeenCalled(); + expect(component.session).toBe(mockSession); + }); + + it("should show error dialog when no active session found", async () => { + mockFido2UserInterfaceService.getCurrentSession.mockReturnValue(null); + mockDialogService.openSimpleDialog.mockResolvedValue(false); + + await component.ngOnInit(); + + expect(mockDialogService.openSimpleDialog).toHaveBeenCalledWith({ + title: { key: "unableToSavePasskey" }, + content: { key: "closeThisBitwardenWindow" }, + type: "danger", + acceptButtonText: { key: "closeThisWindow" }, + acceptAction: expect.any(Function), + cancelButtonText: null, + }); + }); + }); + + describe("addCredentialToCipher", () => { + beforeEach(() => { + component.session = mockSession; + }); + + it("should add passkey to cipher", async () => { + const cipher = createMockCiphers()[0]; + + await component.addCredentialToCipher(cipher); + + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(true, cipher); + }); + + it("should not add passkey when password reprompt is cancelled", async () => { + const cipher = createMockCiphers()[0]; + cipher.reprompt = CipherRepromptType.Password; + mockPasswordRepromptService.showPasswordPrompt.mockResolvedValue(false); + + await component.addCredentialToCipher(cipher); + + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(false, cipher); + }); + + it("should call openSimpleDialog when cipher already has a fido2 credential", async () => { + const cipher = createMockCiphers()[0]; + Object.defineProperty(cipher.login, "hasFido2Credentials", { + get: jest.fn().mockReturnValue(true), + }); + mockDialogService.openSimpleDialog.mockResolvedValue(true); + + await component.addCredentialToCipher(cipher); + + expect(mockDialogService.openSimpleDialog).toHaveBeenCalledWith({ + title: { key: "overwritePasskey" }, + content: { key: "alreadyContainsPasskey" }, + type: "warning", + }); + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(true, cipher); + }); + + it("should not add passkey when user cancels overwrite dialog", async () => { + const cipher = createMockCiphers()[0]; + Object.defineProperty(cipher.login, "hasFido2Credentials", { + get: jest.fn().mockReturnValue(true), + }); + mockDialogService.openSimpleDialog.mockResolvedValue(false); + + await component.addCredentialToCipher(cipher); + + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(false, cipher); + }); + }); + + describe("confirmPasskey", () => { + beforeEach(() => { + component.session = mockSession; + }); + + it("should confirm passkey creation successfully", async () => { + await component.confirmPasskey(); + + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(true); + }); + + it("should call openSimpleDialog when session is null", async () => { + component.session = null; + mockDialogService.openSimpleDialog.mockResolvedValue(false); + + await component.confirmPasskey(); + + expect(mockDialogService.openSimpleDialog).toHaveBeenCalledWith({ + title: { key: "unableToSavePasskey" }, + content: { key: "closeThisBitwardenWindow" }, + type: "danger", + acceptButtonText: { key: "closeThisWindow" }, + acceptAction: expect.any(Function), + cancelButtonText: null, + }); + }); + }); + + describe("closeModal", () => { + it("should close modal and notify session", async () => { + component.session = mockSession; + + await component.closeModal(); + + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(false); + expect(mockSession.confirmChosenCipher).toHaveBeenCalledWith(null); + }); + }); +}); diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-create.component.ts b/apps/desktop/src/autofill/modal/credentials/fido2-create.component.ts new file mode 100644 index 00000000000..3bb8fe4f418 --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-create.component.ts @@ -0,0 +1,219 @@ +import { CommonModule } from "@angular/common"; +import { Component, OnInit, OnDestroy } from "@angular/core"; +import { RouterModule, Router } from "@angular/router"; +import { combineLatest, map, Observable, Subject, switchMap } from "rxjs"; + +import { JslibModule } from "@bitwarden/angular/jslib.module"; +import { BitwardenShield, NoResults } from "@bitwarden/assets/svg"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service"; +import { Fido2Utils } from "@bitwarden/common/platform/services/fido2/fido2-utils"; +import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { CipherType } from "@bitwarden/common/vault/enums/cipher-type"; +import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { + DialogService, + BadgeModule, + ButtonModule, + DialogModule, + IconModule, + ItemModule, + SectionComponent, + TableModule, + SectionHeaderComponent, + BitIconButtonComponent, + SimpleDialogOptions, +} from "@bitwarden/components"; +import { PasswordRepromptService } from "@bitwarden/vault"; + +import { DesktopAutofillService } from "../../../autofill/services/desktop-autofill.service"; +import { DesktopSettingsService } from "../../../platform/services/desktop-settings.service"; +import { + DesktopFido2UserInterfaceService, + DesktopFido2UserInterfaceSession, +} from "../../services/desktop-fido2-user-interface.service"; + +// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection +@Component({ + standalone: true, + imports: [ + CommonModule, + RouterModule, + SectionHeaderComponent, + BitIconButtonComponent, + TableModule, + JslibModule, + IconModule, + ButtonModule, + DialogModule, + SectionComponent, + ItemModule, + BadgeModule, + ], + templateUrl: "fido2-create.component.html", +}) +export class Fido2CreateComponent implements OnInit, OnDestroy { + session?: DesktopFido2UserInterfaceSession = null; + ciphers$: Observable; + private destroy$ = new Subject(); + readonly Icons = { BitwardenShield, NoResults }; + + private get DIALOG_MESSAGES() { + return { + unexpectedErrorShort: { + title: { key: "unexpectedErrorShort" }, + content: { key: "closeThisBitwardenWindow" }, + type: "danger", + acceptButtonText: { key: "closeThisWindow" }, + cancelButtonText: null as null, + acceptAction: async () => this.dialogService.closeAll(), + }, + unableToSavePasskey: { + title: { key: "unableToSavePasskey" }, + content: { key: "closeThisBitwardenWindow" }, + type: "danger", + acceptButtonText: { key: "closeThisWindow" }, + cancelButtonText: null as null, + acceptAction: async () => this.dialogService.closeAll(), + }, + overwritePasskey: { + title: { key: "overwritePasskey" }, + content: { key: "alreadyContainsPasskey" }, + type: "warning", + }, + } as const satisfies Record; + } + + constructor( + private readonly desktopSettingsService: DesktopSettingsService, + private readonly fido2UserInterfaceService: DesktopFido2UserInterfaceService, + private readonly accountService: AccountService, + private readonly cipherService: CipherService, + private readonly desktopAutofillService: DesktopAutofillService, + private readonly dialogService: DialogService, + private readonly domainSettingsService: DomainSettingsService, + private readonly passwordRepromptService: PasswordRepromptService, + private readonly router: Router, + ) {} + + async ngOnInit(): Promise { + this.session = this.fido2UserInterfaceService.getCurrentSession(); + + if (this.session) { + const rpid = await this.session.getRpId(); + this.initializeCiphersObservable(rpid); + } else { + await this.showErrorDialog(this.DIALOG_MESSAGES.unableToSavePasskey); + } + } + + async ngOnDestroy(): Promise { + this.destroy$.next(); + this.destroy$.complete(); + await this.closeModal(); + } + + async addCredentialToCipher(cipher: CipherView): Promise { + const isConfirmed = await this.validateCipherAccess(cipher); + + try { + if (!this.session) { + throw new Error("Missing session"); + } + + this.session.notifyConfirmCreateCredential(isConfirmed, cipher); + } catch { + await this.showErrorDialog(this.DIALOG_MESSAGES.unableToSavePasskey); + return; + } + + await this.closeModal(); + } + + async confirmPasskey(): Promise { + try { + if (!this.session) { + throw new Error("Missing session"); + } + + this.session.notifyConfirmCreateCredential(true); + } catch { + await this.showErrorDialog(this.DIALOG_MESSAGES.unableToSavePasskey); + } + + await this.closeModal(); + } + + async closeModal(): Promise { + await this.desktopSettingsService.setModalMode(false); + await this.accountService.setShowHeader(true); + + if (this.session) { + this.session.notifyConfirmCreateCredential(false); + this.session.confirmChosenCipher(null); + } + + await this.router.navigate(["/"]); + } + + private initializeCiphersObservable(rpid: string): void { + const lastRegistrationRequest = this.desktopAutofillService.lastRegistrationRequest; + + if (!lastRegistrationRequest || !rpid) { + return; + } + + const userHandle = Fido2Utils.bufferToString( + new Uint8Array(lastRegistrationRequest.userHandle), + ); + + this.ciphers$ = combineLatest([ + this.accountService.activeAccount$.pipe(map((a) => a?.id)), + this.domainSettingsService.getUrlEquivalentDomains(rpid), + ]).pipe( + switchMap(async ([activeUserId, equivalentDomains]) => { + if (!activeUserId) { + return []; + } + + try { + const allCiphers = await this.cipherService.getAllDecrypted(activeUserId); + return allCiphers.filter( + (cipher) => + cipher != null && + cipher.type == CipherType.Login && + cipher.login?.matchesUri(rpid, equivalentDomains) && + Fido2Utils.cipherHasNoOtherPasskeys(cipher, userHandle) && + !cipher.deletedDate, + ); + } catch { + await this.showErrorDialog(this.DIALOG_MESSAGES.unexpectedErrorShort); + return []; + } + }), + ); + } + + private async validateCipherAccess(cipher: CipherView): Promise { + if (cipher.login.hasFido2Credentials) { + const overwriteConfirmed = await this.dialogService.openSimpleDialog( + this.DIALOG_MESSAGES.overwritePasskey, + ); + + if (!overwriteConfirmed) { + return false; + } + } + + if (cipher.reprompt) { + return this.passwordRepromptService.showPasswordPrompt(); + } + + return true; + } + + private async showErrorDialog(config: SimpleDialogOptions): Promise { + await this.dialogService.openSimpleDialog(config); + await this.closeModal(); + } +} diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.html b/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.html new file mode 100644 index 00000000000..792934deedc --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.html @@ -0,0 +1,44 @@ +
+ + +
+ + +

+ {{ "savePasskeyQuestion" | i18n }} +

+
+ + +
+
+ +
+ +
+ +
+ {{ "passkeyAlreadyExists" | i18n }} + {{ "applicationDoesNotSupportDuplicates" | i18n }} +
+ +
+
+
+
diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.spec.ts b/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.spec.ts new file mode 100644 index 00000000000..6a465136458 --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.spec.ts @@ -0,0 +1,78 @@ +import { NO_ERRORS_SCHEMA } from "@angular/core"; +import { ComponentFixture, TestBed } from "@angular/core/testing"; +import { Router } from "@angular/router"; +import { mock, MockProxy } from "jest-mock-extended"; + +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; + +import { DesktopSettingsService } from "../../../platform/services/desktop-settings.service"; +import { + DesktopFido2UserInterfaceService, + DesktopFido2UserInterfaceSession, +} from "../../services/desktop-fido2-user-interface.service"; + +import { Fido2ExcludedCiphersComponent } from "./fido2-excluded-ciphers.component"; + +describe("Fido2ExcludedCiphersComponent", () => { + let component: Fido2ExcludedCiphersComponent; + let fixture: ComponentFixture; + let mockDesktopSettingsService: MockProxy; + let mockFido2UserInterfaceService: MockProxy; + let mockAccountService: MockProxy; + let mockRouter: MockProxy; + let mockSession: MockProxy; + let mockI18nService: MockProxy; + + beforeEach(async () => { + mockDesktopSettingsService = mock(); + mockFido2UserInterfaceService = mock(); + mockAccountService = mock(); + mockRouter = mock(); + mockSession = mock(); + mockI18nService = mock(); + + mockFido2UserInterfaceService.getCurrentSession.mockReturnValue(mockSession); + + await TestBed.configureTestingModule({ + imports: [Fido2ExcludedCiphersComponent], + providers: [ + { provide: DesktopSettingsService, useValue: mockDesktopSettingsService }, + { provide: DesktopFido2UserInterfaceService, useValue: mockFido2UserInterfaceService }, + { provide: AccountService, useValue: mockAccountService }, + { provide: Router, useValue: mockRouter }, + { provide: I18nService, useValue: mockI18nService }, + ], + schemas: [NO_ERRORS_SCHEMA], + }).compileComponents(); + + fixture = TestBed.createComponent(Fido2ExcludedCiphersComponent); + component = fixture.componentInstance; + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + describe("ngOnInit", () => { + it("should initialize session", async () => { + await component.ngOnInit(); + + expect(mockFido2UserInterfaceService.getCurrentSession).toHaveBeenCalled(); + expect(component.session).toBe(mockSession); + }); + }); + + describe("closeModal", () => { + it("should close modal and notify session when session exists", async () => { + component.session = mockSession; + + await component.closeModal(); + + expect(mockDesktopSettingsService.setModalMode).toHaveBeenCalledWith(false); + expect(mockAccountService.setShowHeader).toHaveBeenCalledWith(true); + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(false); + expect(mockRouter.navigate).toHaveBeenCalledWith(["/"]); + }); + }); +}); diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.ts b/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.ts new file mode 100644 index 00000000000..7b4f5be0e4c --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-excluded-ciphers.component.ts @@ -0,0 +1,78 @@ +import { CommonModule } from "@angular/common"; +import { Component, OnInit, OnDestroy } from "@angular/core"; +import { RouterModule, Router } from "@angular/router"; + +import { JslibModule } from "@bitwarden/angular/jslib.module"; +import { BitwardenShield, NoResults } from "@bitwarden/assets/svg"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { + BadgeModule, + ButtonModule, + DialogModule, + IconModule, + ItemModule, + SectionComponent, + TableModule, + SectionHeaderComponent, + BitIconButtonComponent, +} from "@bitwarden/components"; + +import { DesktopSettingsService } from "../../../platform/services/desktop-settings.service"; +import { + DesktopFido2UserInterfaceService, + DesktopFido2UserInterfaceSession, +} from "../../services/desktop-fido2-user-interface.service"; + +// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection +@Component({ + standalone: true, + imports: [ + CommonModule, + RouterModule, + SectionHeaderComponent, + BitIconButtonComponent, + TableModule, + JslibModule, + IconModule, + ButtonModule, + DialogModule, + SectionComponent, + ItemModule, + BadgeModule, + ], + templateUrl: "fido2-excluded-ciphers.component.html", +}) +export class Fido2ExcludedCiphersComponent implements OnInit, OnDestroy { + session?: DesktopFido2UserInterfaceSession = null; + readonly Icons = { BitwardenShield, NoResults }; + + constructor( + private readonly desktopSettingsService: DesktopSettingsService, + private readonly fido2UserInterfaceService: DesktopFido2UserInterfaceService, + private readonly accountService: AccountService, + private readonly router: Router, + ) {} + + async ngOnInit(): Promise { + this.session = this.fido2UserInterfaceService.getCurrentSession(); + } + + async ngOnDestroy(): Promise { + await this.closeModal(); + } + + async closeModal(): Promise { + // Clean up modal state + await this.desktopSettingsService.setModalMode(false); + await this.accountService.setShowHeader(true); + + // Clean up session state + if (this.session) { + this.session.notifyConfirmCreateCredential(false); + this.session.confirmChosenCipher(null); + } + + // Navigate away + await this.router.navigate(["/"]); + } +} diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.html b/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.html new file mode 100644 index 00000000000..ed04993d09f --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.html @@ -0,0 +1,37 @@ +
+ + +
+ + +

{{ "passkeyLogin" | i18n }}

+
+ +
+
+ + + + + {{ c.subTitle }} + {{ "select" | i18n }} + + + +
diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.spec.ts b/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.spec.ts new file mode 100644 index 00000000000..70ef4461f6a --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.spec.ts @@ -0,0 +1,196 @@ +import { NO_ERRORS_SCHEMA } from "@angular/core"; +import { ComponentFixture, TestBed } from "@angular/core/testing"; +import { Router } from "@angular/router"; +import { mock, MockProxy } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { AccountService, Account } from "@bitwarden/common/auth/abstractions/account.service"; +import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums"; +import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { PasswordRepromptService } from "@bitwarden/vault"; + +import { DesktopSettingsService } from "../../../platform/services/desktop-settings.service"; +import { + DesktopFido2UserInterfaceService, + DesktopFido2UserInterfaceSession, +} from "../../services/desktop-fido2-user-interface.service"; + +import { Fido2VaultComponent } from "./fido2-vault.component"; + +describe("Fido2VaultComponent", () => { + let component: Fido2VaultComponent; + let fixture: ComponentFixture; + let mockDesktopSettingsService: MockProxy; + let mockFido2UserInterfaceService: MockProxy; + let mockCipherService: MockProxy; + let mockAccountService: MockProxy; + let mockLogService: MockProxy; + let mockPasswordRepromptService: MockProxy; + let mockRouter: MockProxy; + let mockSession: MockProxy; + let mockI18nService: MockProxy; + + const mockActiveAccount = { id: "test-user-id", email: "test@example.com" }; + const mockCipherIds = ["cipher-1", "cipher-2", "cipher-3"]; + + beforeEach(async () => { + mockDesktopSettingsService = mock(); + mockFido2UserInterfaceService = mock(); + mockCipherService = mock(); + mockAccountService = mock(); + mockLogService = mock(); + mockPasswordRepromptService = mock(); + mockRouter = mock(); + mockSession = mock(); + mockI18nService = mock(); + + mockAccountService.activeAccount$ = of(mockActiveAccount as Account); + mockFido2UserInterfaceService.getCurrentSession.mockReturnValue(mockSession); + mockSession.availableCipherIds$ = of(mockCipherIds); + mockCipherService.cipherListViews$ = jest.fn().mockReturnValue(of([])); + + await TestBed.configureTestingModule({ + imports: [Fido2VaultComponent], + providers: [ + { provide: DesktopSettingsService, useValue: mockDesktopSettingsService }, + { provide: DesktopFido2UserInterfaceService, useValue: mockFido2UserInterfaceService }, + { provide: CipherService, useValue: mockCipherService }, + { provide: AccountService, useValue: mockAccountService }, + { provide: LogService, useValue: mockLogService }, + { provide: PasswordRepromptService, useValue: mockPasswordRepromptService }, + { provide: Router, useValue: mockRouter }, + { provide: I18nService, useValue: mockI18nService }, + ], + schemas: [NO_ERRORS_SCHEMA], + }).compileComponents(); + + fixture = TestBed.createComponent(Fido2VaultComponent); + component = fixture.componentInstance; + }); + + const mockCiphers: any[] = [ + { + id: "cipher-1", + name: "Test Cipher 1", + type: CipherType.Login, + login: { + username: "test1@example.com", + }, + reprompt: CipherRepromptType.None, + deletedDate: null, + }, + { + id: "cipher-2", + name: "Test Cipher 2", + type: CipherType.Login, + login: { + username: "test2@example.com", + }, + reprompt: CipherRepromptType.None, + deletedDate: null, + }, + { + id: "cipher-3", + name: "Test Cipher 3", + type: CipherType.Login, + login: { + username: "test3@example.com", + }, + reprompt: CipherRepromptType.Password, + deletedDate: null, + }, + ]; + + describe("ngOnInit", () => { + it("should initialize session and load ciphers successfully", async () => { + mockCipherService.cipherListViews$ = jest.fn().mockReturnValue(of(mockCiphers)); + + await component.ngOnInit(); + + expect(mockFido2UserInterfaceService.getCurrentSession).toHaveBeenCalled(); + expect(component.session).toBe(mockSession); + expect(component.cipherIds$).toBe(mockSession.availableCipherIds$); + expect(mockCipherService.cipherListViews$).toHaveBeenCalledWith(mockActiveAccount.id); + }); + + it("should handle when no active session found", async () => { + mockFido2UserInterfaceService.getCurrentSession.mockReturnValue(null); + + await component.ngOnInit(); + + expect(component.session).toBeNull(); + }); + + it("should filter out deleted ciphers", async () => { + const ciphersWithDeleted = [ + ...mockCiphers.slice(0, 1), + { ...mockCiphers[1], deletedDate: new Date() }, + ...mockCiphers.slice(2), + ]; + mockCipherService.cipherListViews$ = jest.fn().mockReturnValue(of(ciphersWithDeleted)); + + await component.ngOnInit(); + await new Promise((resolve) => setTimeout(resolve, 0)); + + let ciphersResult: CipherView[] = []; + component.ciphers$.subscribe((ciphers) => { + ciphersResult = ciphers; + }); + + expect(ciphersResult).toHaveLength(2); + expect(ciphersResult.every((cipher) => !cipher.deletedDate)).toBe(true); + }); + }); + + describe("chooseCipher", () => { + const cipher = mockCiphers[0]; + + beforeEach(() => { + component.session = mockSession; + }); + + it("should choose cipher when access is validated", async () => { + cipher.reprompt = CipherRepromptType.None; + + await component.chooseCipher(cipher); + + expect(mockSession.confirmChosenCipher).toHaveBeenCalledWith(cipher.id, true); + expect(mockRouter.navigate).toHaveBeenCalledWith(["/"]); + }); + + it("should prompt for password when cipher requires reprompt", async () => { + cipher.reprompt = CipherRepromptType.Password; + mockPasswordRepromptService.showPasswordPrompt.mockResolvedValue(true); + + await component.chooseCipher(cipher); + + expect(mockPasswordRepromptService.showPasswordPrompt).toHaveBeenCalled(); + expect(mockSession.confirmChosenCipher).toHaveBeenCalledWith(cipher.id, true); + }); + + it("should not choose cipher when password reprompt is cancelled", async () => { + cipher.reprompt = CipherRepromptType.Password; + mockPasswordRepromptService.showPasswordPrompt.mockResolvedValue(false); + + await component.chooseCipher(cipher); + + expect(mockPasswordRepromptService.showPasswordPrompt).toHaveBeenCalled(); + expect(mockSession.confirmChosenCipher).toHaveBeenCalledWith(cipher.id, false); + }); + }); + + describe("closeModal", () => { + it("should close modal and notify session", async () => { + component.session = mockSession; + + await component.closeModal(); + + expect(mockRouter.navigate).toHaveBeenCalledWith(["/"]); + expect(mockSession.notifyConfirmCreateCredential).toHaveBeenCalledWith(false); + expect(mockSession.confirmChosenCipher).toHaveBeenCalledWith(null); + }); + }); +}); diff --git a/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.ts b/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.ts new file mode 100644 index 00000000000..e04ab4e7e04 --- /dev/null +++ b/apps/desktop/src/autofill/modal/credentials/fido2-vault.component.ts @@ -0,0 +1,161 @@ +import { CommonModule } from "@angular/common"; +import { Component, OnInit, OnDestroy } from "@angular/core"; +import { RouterModule, Router } from "@angular/router"; +import { + firstValueFrom, + map, + combineLatest, + of, + BehaviorSubject, + Observable, + Subject, + takeUntil, +} from "rxjs"; + +import { JslibModule } from "@bitwarden/angular/jslib.module"; +import { BitwardenShield } from "@bitwarden/assets/svg"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { CipherRepromptType } from "@bitwarden/common/vault/enums"; +import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { + BadgeModule, + ButtonModule, + DialogModule, + DialogService, + IconModule, + ItemModule, + SectionComponent, + TableModule, + BitIconButtonComponent, + SectionHeaderComponent, +} from "@bitwarden/components"; +import { PasswordRepromptService } from "@bitwarden/vault"; + +import { DesktopSettingsService } from "../../../platform/services/desktop-settings.service"; +import { + DesktopFido2UserInterfaceService, + DesktopFido2UserInterfaceSession, +} from "../../services/desktop-fido2-user-interface.service"; + +// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection +@Component({ + standalone: true, + imports: [ + CommonModule, + RouterModule, + SectionHeaderComponent, + BitIconButtonComponent, + TableModule, + JslibModule, + IconModule, + ButtonModule, + DialogModule, + SectionComponent, + ItemModule, + BadgeModule, + ], + templateUrl: "fido2-vault.component.html", +}) +export class Fido2VaultComponent implements OnInit, OnDestroy { + session?: DesktopFido2UserInterfaceSession = null; + private destroy$ = new Subject(); + private ciphersSubject = new BehaviorSubject([]); + ciphers$: Observable = this.ciphersSubject.asObservable(); + cipherIds$: Observable | undefined; + readonly Icons = { BitwardenShield }; + + constructor( + private readonly desktopSettingsService: DesktopSettingsService, + private readonly fido2UserInterfaceService: DesktopFido2UserInterfaceService, + private readonly cipherService: CipherService, + private readonly accountService: AccountService, + private readonly dialogService: DialogService, + private readonly logService: LogService, + private readonly passwordRepromptService: PasswordRepromptService, + private readonly router: Router, + ) {} + + async ngOnInit(): Promise { + this.session = this.fido2UserInterfaceService.getCurrentSession(); + this.cipherIds$ = this.session?.availableCipherIds$; + await this.loadCiphers(); + } + + async ngOnDestroy(): Promise { + this.destroy$.next(); + this.destroy$.complete(); + } + + async chooseCipher(cipher: CipherView): Promise { + if (!this.session) { + await this.dialogService.openSimpleDialog({ + title: { key: "unexpectedErrorShort" }, + content: { key: "closeThisBitwardenWindow" }, + type: "danger", + acceptButtonText: { key: "closeThisWindow" }, + cancelButtonText: null, + }); + await this.closeModal(); + + return; + } + + const isConfirmed = await this.validateCipherAccess(cipher); + this.session.confirmChosenCipher(cipher.id, isConfirmed); + + await this.closeModal(); + } + + async closeModal(): Promise { + await this.desktopSettingsService.setModalMode(false); + await this.accountService.setShowHeader(true); + + if (this.session) { + this.session.notifyConfirmCreateCredential(false); + this.session.confirmChosenCipher(null); + } + + await this.router.navigate(["/"]); + } + + private async loadCiphers(): Promise { + const activeUserId = await firstValueFrom( + this.accountService.activeAccount$.pipe(map((a) => a?.id)), + ); + + if (!activeUserId) { + return; + } + + // Combine cipher list with optional cipher IDs filter + combineLatest([this.cipherService.cipherListViews$(activeUserId), this.cipherIds$ || of(null)]) + .pipe( + map(([ciphers, cipherIds]) => { + // Filter out deleted ciphers + const activeCiphers = ciphers.filter((cipher) => !cipher.deletedDate); + + // If specific IDs provided, filter by them + if (cipherIds?.length > 0) { + return activeCiphers.filter((cipher) => cipherIds.includes(cipher.id as string)); + } + + return activeCiphers; + }), + takeUntil(this.destroy$), + ) + .subscribe({ + next: (ciphers) => this.ciphersSubject.next(ciphers as CipherView[]), + error: (error: unknown) => this.logService.error("Failed to load ciphers", error), + }); + } + + private async validateCipherAccess(cipher: CipherView): Promise { + if (cipher.reprompt !== CipherRepromptType.None) { + return this.passwordRepromptService.showPasswordPrompt(); + } + + return true; + } +} diff --git a/apps/desktop/src/autofill/preload.ts b/apps/desktop/src/autofill/preload.ts index fcb2f646743..d9f283b7d08 100644 --- a/apps/desktop/src/autofill/preload.ts +++ b/apps/desktop/src/autofill/preload.ts @@ -9,6 +9,8 @@ export default { runCommand: (params: RunCommandParams): Promise> => ipcRenderer.invoke("autofill.runCommand", params), + listenerReady: () => ipcRenderer.send("autofill.listenerReady"), + listenPasskeyRegistration: ( fn: ( clientId: number, @@ -127,6 +129,25 @@ export default { }, ); }, + + listenNativeStatus: ( + fn: (clientId: number, sequenceNumber: number, status: { key: string; value: string }) => void, + ) => { + ipcRenderer.on( + "autofill.nativeStatus", + ( + event, + data: { + clientId: number; + sequenceNumber: number; + status: { key: string; value: string }; + }, + ) => { + const { clientId, sequenceNumber, status } = data; + fn(clientId, sequenceNumber, status); + }, + ); + }, configureAutotype: (enabled: boolean, keyboardShortcut: string[]) => { ipcRenderer.send("autofill.configureAutotype", { enabled, keyboardShortcut }); }, diff --git a/apps/desktop/src/autofill/services/desktop-autofill.service.ts b/apps/desktop/src/autofill/services/desktop-autofill.service.ts index 5500bc58f5a..4823458b972 100644 --- a/apps/desktop/src/autofill/services/desktop-autofill.service.ts +++ b/apps/desktop/src/autofill/services/desktop-autofill.service.ts @@ -1,6 +1,8 @@ import { Injectable, OnDestroy } from "@angular/core"; import { Subject, + combineLatest, + debounceTime, distinctUntilChanged, filter, firstValueFrom, @@ -8,11 +10,13 @@ import { mergeMap, switchMap, takeUntil, - EMPTY, } from "rxjs"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; +import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { getOptionalUserId } from "@bitwarden/common/auth/services/account.service"; +import { DeviceType } from "@bitwarden/common/enums"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; @@ -43,9 +47,15 @@ import { import type { NativeWindowObject } from "./desktop-fido2-user-interface.service"; +const NativeCredentialSyncFeatureFlag = + ipc.platform.deviceType === DeviceType.WindowsDesktop + ? FeatureFlag.WindowsNativeCredentialSync + : FeatureFlag.MacOsNativeCredentialSync; + @Injectable() export class DesktopAutofillService implements OnDestroy { private destroy$ = new Subject(); + private registrationRequest: autofill.PasskeyRegistrationRequest; constructor( private logService: LogService, @@ -53,35 +63,64 @@ export class DesktopAutofillService implements OnDestroy { private configService: ConfigService, private fido2AuthenticatorService: Fido2AuthenticatorServiceAbstraction, private accountService: AccountService, + private authService: AuthService, ) {} async init() { this.configService - .getFeatureFlag$(FeatureFlag.MacOsNativeCredentialSync) + .getFeatureFlag$(NativeCredentialSyncFeatureFlag) .pipe( distinctUntilChanged(), - switchMap((enabled) => { - if (!enabled) { - return EMPTY; - } - - return this.accountService.activeAccount$.pipe( - map((account) => account?.id), - filter((userId): userId is UserId => userId != null), - switchMap((userId) => this.cipherService.cipherViews$(userId)), + filter((enabled) => enabled === true), // Only proceed if feature is enabled + switchMap(() => { + return combineLatest([ + this.accountService.activeAccount$.pipe( + map((account) => account?.id), + filter((userId): userId is UserId => userId != null), + ), + this.authService.activeAccountStatus$, + ]).pipe( + // Only proceed when the vault is unlocked + filter(([, status]) => status === AuthenticationStatus.Unlocked), + // Then get cipher views + switchMap(([userId]) => this.cipherService.cipherViews$(userId)), ); }), - // TODO: This will unset all the autofill credentials on the OS - // when the account locks. We should instead explicilty clear the credentials - // when the user logs out. Maybe by subscribing to the encrypted ciphers observable instead. + debounceTime(100), // just a precaution to not spam the sync if there are multiple changes (we typically observe a null change) + // No filter for empty arrays here - we want to sync even if there are 0 items + filter((cipherViewMap) => cipherViewMap !== null), + mergeMap((cipherViewMap) => this.sync(Object.values(cipherViewMap ?? []))), takeUntil(this.destroy$), ) .subscribe(); + // Listen for sign out to clear credentials + this.authService.activeAccountStatus$ + .pipe( + filter((status) => status === AuthenticationStatus.LoggedOut), + mergeMap(() => this.sync([])), // sync an empty array + takeUntil(this.destroy$), + ) + .subscribe(); + this.listenIpc(); } + async adHocSync(): Promise { + this.logService.debug("Performing AdHoc sync"); + const account = await firstValueFrom(this.accountService.activeAccount$); + const userId = account?.id; + + if (!userId) { + throw new Error("No active user found"); + } + + const cipherViewMap = await firstValueFrom(this.cipherService.cipherViews$(userId)); + this.logService.info("Performing AdHoc sync", Object.values(cipherViewMap ?? [])); + await this.sync(Object.values(cipherViewMap ?? [])); + } + /** Give metadata about all available credentials in the users vault */ async sync(cipherViews: CipherView[]) { const status = await this.status(); @@ -94,8 +133,8 @@ export class DesktopAutofillService implements OnDestroy { return; } - let fido2Credentials: NativeAutofillFido2Credential[]; - let passwordCredentials: NativeAutofillPasswordCredential[]; + let fido2Credentials: NativeAutofillFido2Credential[] = []; + let passwordCredentials: NativeAutofillPasswordCredential[] = []; if (status.value.support.password) { passwordCredentials = cipherViews @@ -122,6 +161,11 @@ export class DesktopAutofillService implements OnDestroy { })); } + this.logService.info("Syncing autofill credentials", { + fido2Credentials, + passwordCredentials, + }); + const syncResult = await ipc.autofill.runCommand({ namespace: "autofill", command: "sync", @@ -147,107 +191,155 @@ export class DesktopAutofillService implements OnDestroy { }); } + get lastRegistrationRequest() { + return this.registrationRequest; + } + listenIpc() { - ipc.autofill.listenPasskeyRegistration((clientId, sequenceNumber, request, callback) => { - this.logService.warning("listenPasskeyRegistration", clientId, sequenceNumber, request); - this.logService.warning( - "listenPasskeyRegistration2", - this.convertRegistrationRequest(request), - ); + this.logService.debug("Setting up Native -> Electron IPC Handlers"); + ipc.autofill.listenPasskeyRegistration(async (clientId, sequenceNumber, request, callback) => { + if (!(await this.configService.getFeatureFlag(NativeCredentialSyncFeatureFlag))) { + this.logService.debug( + `listenPasskeyRegistration: ${NativeCredentialSyncFeatureFlag} feature flag is disabled`, + ); + callback(new Error(`${NativeCredentialSyncFeatureFlag} feature flag is disabled`), null); + return; + } + + this.registrationRequest = request; + + this.logService.debug("listenPasskeyRegistration", clientId, sequenceNumber, request); + this.logService.debug("listenPasskeyRegistration2", this.convertRegistrationRequest(request)); const controller = new AbortController(); - void this.fido2AuthenticatorService - .makeCredential( + + try { + const response = await this.fido2AuthenticatorService.makeCredential( this.convertRegistrationRequest(request), { windowXy: request.windowXy }, controller, - ) - .then((response) => { - callback(null, this.convertRegistrationResponse(request, response)); - }) - .catch((error) => { - this.logService.error("listenPasskeyRegistration error", error); - callback(error, null); - }); + ); + + this.logService.debug("Sending registration response to plugin via callback"); + callback(null, this.convertRegistrationResponse(request, response)); + } catch (error) { + this.logService.error("listenPasskeyRegistration error", error); + callback(error, null); + } + this.logService.info("Passkey registration completed."); }); ipc.autofill.listenPasskeyAssertionWithoutUserInterface( async (clientId, sequenceNumber, request, callback) => { - this.logService.warning( + if (!(await this.configService.getFeatureFlag(NativeCredentialSyncFeatureFlag))) { + this.logService.debug( + `listenPasskeyAssertionWithoutUserInterface: ${NativeCredentialSyncFeatureFlag} feature flag is disabled`, + ); + callback(new Error(`${NativeCredentialSyncFeatureFlag} feature flag is disabled`), null); + return; + } + + this.logService.debug( "listenPasskeyAssertion without user interface", clientId, sequenceNumber, request, ); - // For some reason the credentialId is passed as an empty array in the request, so we need to - // get it from the cipher. For that we use the recordIdentifier, which is the cipherId. - if (request.recordIdentifier && request.credentialId.length === 0) { - const activeUserId = await firstValueFrom( - this.accountService.activeAccount$.pipe(getOptionalUserId), - ); - if (!activeUserId) { - this.logService.error("listenPasskeyAssertion error", "Active user not found"); - callback(new Error("Active user not found"), null); - return; - } - - const cipher = await this.cipherService.get(request.recordIdentifier, activeUserId); - if (!cipher) { - this.logService.error("listenPasskeyAssertion error", "Cipher not found"); - callback(new Error("Cipher not found"), null); - return; - } - - const decrypted = await this.cipherService.decrypt(cipher, activeUserId); - - const fido2Credential = decrypted.login.fido2Credentials?.[0]; - if (!fido2Credential) { - this.logService.error("listenPasskeyAssertion error", "Fido2Credential not found"); - callback(new Error("Fido2Credential not found"), null); - return; - } - - request.credentialId = Array.from( - new Uint8Array(parseCredentialId(decrypted.login.fido2Credentials?.[0].credentialId)), - ); - } - const controller = new AbortController(); - void this.fido2AuthenticatorService - .getAssertion( - this.convertAssertionRequest(request), + + try { + // For some reason the credentialId is passed as an empty array in the request, so we need to + // get it from the cipher. For that we use the recordIdentifier, which is the cipherId. + if (request.recordIdentifier && request.credentialId.length === 0) { + const activeUserId = await firstValueFrom( + this.accountService.activeAccount$.pipe(getOptionalUserId), + ); + if (!activeUserId) { + this.logService.error("listenPasskeyAssertion error", "Active user not found"); + callback(new Error("Active user not found"), null); + return; + } + + const cipher = await this.cipherService.get(request.recordIdentifier, activeUserId); + if (!cipher) { + this.logService.error("listenPasskeyAssertion error", "Cipher not found"); + callback(new Error("Cipher not found"), null); + return; + } + + const decrypted = await this.cipherService.decrypt(cipher, activeUserId); + + const fido2Credential = decrypted.login.fido2Credentials?.[0]; + if (!fido2Credential) { + this.logService.error("listenPasskeyAssertion error", "Fido2Credential not found"); + callback(new Error("Fido2Credential not found"), null); + return; + } + + request.credentialId = Array.from( + new Uint8Array(parseCredentialId(decrypted.login.fido2Credentials?.[0].credentialId)), + ); + } + + const response = await this.fido2AuthenticatorService.getAssertion( + this.convertAssertionRequest(request, true), { windowXy: request.windowXy }, controller, - ) - .then((response) => { - callback(null, this.convertAssertionResponse(request, response)); - }) - .catch((error) => { - this.logService.error("listenPasskeyAssertion error", error); - callback(error, null); - }); + ); + + callback(null, this.convertAssertionResponse(request, response)); + } catch (error) { + this.logService.error("listenPasskeyAssertion error", error); + callback(error, null); + return; + } }, ); ipc.autofill.listenPasskeyAssertion(async (clientId, sequenceNumber, request, callback) => { - this.logService.warning("listenPasskeyAssertion", clientId, sequenceNumber, request); + if (!(await this.configService.getFeatureFlag(NativeCredentialSyncFeatureFlag))) { + this.logService.debug( + `listenPasskeyAssertion: ${NativeCredentialSyncFeatureFlag} feature flag is disabled`, + ); + callback(new Error(`${NativeCredentialSyncFeatureFlag} feature flag is disabled`), null); + return; + } + + this.logService.debug("listenPasskeyAssertion", clientId, sequenceNumber, request); const controller = new AbortController(); - void this.fido2AuthenticatorService - .getAssertion( + try { + const response = await this.fido2AuthenticatorService.getAssertion( this.convertAssertionRequest(request), { windowXy: request.windowXy }, controller, - ) - .then((response) => { - callback(null, this.convertAssertionResponse(request, response)); - }) - .catch((error) => { - this.logService.error("listenPasskeyAssertion error", error); - callback(error, null); - }); + ); + + callback(null, this.convertAssertionResponse(request, response)); + } catch (error) { + this.logService.error("listenPasskeyAssertion error", error); + callback(error, null); + } }); + + // Listen for native status messages + ipc.autofill.listenNativeStatus(async (clientId, sequenceNumber, status) => { + if (!(await this.configService.getFeatureFlag(NativeCredentialSyncFeatureFlag))) { + this.logService.debug( + `listenNativeStatus: ${NativeCredentialSyncFeatureFlag} feature flag is disabled`, + ); + return; + } + + this.logService.info("Received native status", status.key, status.value); + if (status.key === "request-sync") { + // perform ad-hoc sync + await this.adHocSync(); + } + }); + + ipc.autofill.listenerReady(); } private convertRegistrationRequest( @@ -269,7 +361,10 @@ export class DesktopAutofillService implements OnDestroy { alg, type: "public-key", })), - excludeCredentialDescriptorList: [], + excludeCredentialDescriptorList: request.excludedCredentials.map((credentialId) => ({ + id: new Uint8Array(credentialId), + type: "public-key" as const, + })), requireResidentKey: true, requireUserVerification: request.userVerification === "required" || request.userVerification === "preferred", @@ -301,18 +396,19 @@ export class DesktopAutofillService implements OnDestroy { request: | autofill.PasskeyAssertionRequest | autofill.PasskeyAssertionWithoutUserInterfaceRequest, + assumeUserPresence: boolean = false, ): Fido2AuthenticatorGetAssertionParams { let allowedCredentials; if ("credentialId" in request) { allowedCredentials = [ { - id: new Uint8Array(request.credentialId), + id: new Uint8Array(request.credentialId).buffer, type: "public-key" as const, }, ]; } else { allowedCredentials = request.allowedCredentials.map((credentialId) => ({ - id: new Uint8Array(credentialId), + id: new Uint8Array(credentialId).buffer, type: "public-key" as const, })); } @@ -325,7 +421,7 @@ export class DesktopAutofillService implements OnDestroy { requireUserVerification: request.userVerification === "required" || request.userVerification === "preferred", fallbackSupported: false, - assumeUserPresence: true, // For desktop assertions, it's safe to assume UP has been checked by OS dialogues + assumeUserPresence, }; } diff --git a/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts b/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts index 3caf13fa5b7..19946ab590c 100644 --- a/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts +++ b/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts @@ -66,7 +66,7 @@ export class DesktopFido2UserInterfaceService nativeWindowObject: NativeWindowObject, abortController?: AbortController, ): Promise { - this.logService.warning("newSession", fallbackSupported, abortController, nativeWindowObject); + this.logService.debug("newSession", fallbackSupported, abortController, nativeWindowObject); const session = new DesktopFido2UserInterfaceSession( this.authService, this.cipherService, @@ -94,9 +94,11 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi ) {} private confirmCredentialSubject = new Subject(); - private createdCipher: Cipher; - private availableCipherIdsSubject = new BehaviorSubject(null); + private updatedCipher: CipherView; + + private rpId = new BehaviorSubject(null); + private availableCipherIdsSubject = new BehaviorSubject([""]); /** * Observable that emits available cipher IDs once they're confirmed by the UI */ @@ -114,7 +116,7 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi assumeUserPresence, masterPasswordRepromptRequired, }: PickCredentialParams): Promise<{ cipherId: string; userVerified: boolean }> { - this.logService.warning("pickCredential desktop function", { + this.logService.debug("pickCredential desktop function", { cipherIds, userVerification, assumeUserPresence, @@ -123,6 +125,7 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi try { // Check if we can return the credential without user interaction + await this.accountService.setShowHeader(false); if (assumeUserPresence && cipherIds.length === 1 && !masterPasswordRepromptRequired) { this.logService.debug( "shortcut - Assuming user presence and returning cipherId", @@ -136,22 +139,27 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi // make the cipherIds available to the UI. this.availableCipherIdsSubject.next(cipherIds); - await this.showUi("/passkeys", this.windowObject.windowXy); + await this.showUi("/fido2-assertion", this.windowObject.windowXy, false); const chosenCipherResponse = await this.waitForUiChosenCipher(); this.logService.debug("Received chosen cipher", chosenCipherResponse); return { - cipherId: chosenCipherResponse.cipherId, - userVerified: chosenCipherResponse.userVerified, + cipherId: chosenCipherResponse?.cipherId, + userVerified: chosenCipherResponse?.userVerified, }; } finally { // Make sure to clean up so the app is never stuck in modal mode? await this.desktopSettingsService.setModalMode(false); + await this.accountService.setShowHeader(true); } } + async getRpId(): Promise { + return firstValueFrom(this.rpId.pipe(filter((id) => id != null))); + } + confirmChosenCipher(cipherId: string, userVerified: boolean = false): void { this.chosenCipherSubject.next({ cipherId, userVerified }); this.chosenCipherSubject.complete(); @@ -159,7 +167,7 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi private async waitForUiChosenCipher( timeoutMs: number = 60000, - ): Promise<{ cipherId: string; userVerified: boolean } | undefined> { + ): Promise<{ cipherId?: string; userVerified: boolean } | undefined> { try { return await lastValueFrom(this.chosenCipherSubject.pipe(timeout(timeoutMs))); } catch { @@ -174,7 +182,10 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi /** * Notifies the Fido2UserInterfaceSession that the UI operations has completed and it can return to the OS. */ - notifyConfirmNewCredential(confirmed: boolean): void { + notifyConfirmCreateCredential(confirmed: boolean, updatedCipher?: CipherView): void { + if (updatedCipher) { + this.updatedCipher = updatedCipher; + } this.confirmCredentialSubject.next(confirmed); this.confirmCredentialSubject.complete(); } @@ -195,60 +206,79 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi async confirmNewCredential({ credentialName, userName, + userHandle, userVerification, rpId, }: NewCredentialParams): Promise<{ cipherId: string; userVerified: boolean }> { - this.logService.warning( + this.logService.debug( "confirmNewCredential", credentialName, userName, + userHandle, userVerification, rpId, ); + this.rpId.next(rpId); try { - await this.showUi("/passkeys", this.windowObject.windowXy); + await this.showUi("/fido2-creation", this.windowObject.windowXy, false); // Wait for the UI to wrap up const confirmation = await this.waitForUiNewCredentialConfirmation(); if (!confirmation) { return { cipherId: undefined, userVerified: false }; } - // Create the credential - await this.createCredential({ - credentialName, - userName, - rpId, - userHandle: "", - userVerification, - }); - // wait for 10ms to help RXJS catch up(?) - // We sometimes get a race condition from this.createCredential not updating cipherService in time - //console.log("waiting 10ms.."); - //await new Promise((resolve) => setTimeout(resolve, 10)); - //console.log("Just waited 10ms"); - - // Return the new cipher (this.createdCipher) - return { cipherId: this.createdCipher.id, userVerified: userVerification }; + if (this.updatedCipher) { + await this.updateCredential(this.updatedCipher); + return { cipherId: this.updatedCipher.id, userVerified: userVerification }; + } else { + // Create the cipher + const createdCipher = await this.createCipher({ + credentialName, + userName, + rpId, + userHandle, + userVerification, + }); + return { cipherId: createdCipher.id, userVerified: userVerification }; + } } finally { // Make sure to clean up so the app is never stuck in modal mode? await this.desktopSettingsService.setModalMode(false); + await this.accountService.setShowHeader(true); } } - private async showUi(route: string, position?: { x: number; y: number }): Promise { + private async hideUi(): Promise { + await this.desktopSettingsService.setModalMode(false); + await this.router.navigate(["/"]); + } + + private async showUi( + route: string, + position?: { x: number; y: number }, + showTrafficButtons: boolean = false, + disableRedirect?: boolean, + ): Promise { // Load the UI: - await this.desktopSettingsService.setModalMode(true, position); - await this.router.navigate(["/passkeys"]); + await this.desktopSettingsService.setModalMode(true, showTrafficButtons, position); + await this.accountService.setShowHeader(showTrafficButtons); + await this.router.navigate([ + route, + { + "disable-redirect": disableRedirect || null, + }, + ]); } /** - * Can be called by the UI to create a new credential with user input etc. + * Can be called by the UI to create a new cipher with user input etc. * @param param0 */ - async createCredential({ credentialName, userName, rpId }: NewCredentialParams): Promise { + async createCipher({ credentialName, userName, rpId }: NewCredentialParams): Promise { // Store the passkey on a new cipher to avoid replacing something important + const cipher = new CipherView(); cipher.name = credentialName; @@ -267,32 +297,81 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi this.accountService.activeAccount$.pipe(map((a) => a?.id)), ); + if (!activeUserId) { + throw new Error("No active user ID found!"); + } + const encCipher = await this.cipherService.encrypt(cipher, activeUserId); - const createdCipher = await this.cipherService.createWithServer(encCipher); - this.createdCipher = createdCipher; + try { + const createdCipher = await this.cipherService.createWithServer(encCipher); - return createdCipher; + return createdCipher; + } catch { + throw new Error("Unable to create cipher"); + } + } + + async updateCredential(cipher: CipherView): Promise { + this.logService.info("updateCredential"); + await firstValueFrom( + this.accountService.activeAccount$.pipe( + map(async (a) => { + if (a) { + const encCipher = await this.cipherService.encrypt(cipher, a.id); + await this.cipherService.updateWithServer(encCipher); + } + }), + ), + ); } async informExcludedCredential(existingCipherIds: string[]): Promise { - this.logService.warning("informExcludedCredential", existingCipherIds); + this.logService.debug("informExcludedCredential", existingCipherIds); + + // make the cipherIds available to the UI. + this.availableCipherIdsSubject.next(existingCipherIds); + + await this.accountService.setShowHeader(false); + await this.showUi("/fido2-excluded", this.windowObject.windowXy, false); } async ensureUnlockedVault(): Promise { - this.logService.warning("ensureUnlockedVault"); + this.logService.debug("ensureUnlockedVault"); const status = await firstValueFrom(this.authService.activeAccountStatus$); if (status !== AuthenticationStatus.Unlocked) { - throw new Error("Vault is not unlocked"); + await this.showUi("/lock", this.windowObject.windowXy, true, true); + + let status2: AuthenticationStatus; + try { + status2 = await lastValueFrom( + this.authService.activeAccountStatus$.pipe( + filter((s) => s === AuthenticationStatus.Unlocked), + take(1), + timeout(1000 * 60 * 5), // 5 minutes + ), + ); + } catch (error) { + this.logService.warning("Error while waiting for vault to unlock", error); + } + + if (status2 === AuthenticationStatus.Unlocked) { + await this.router.navigate(["/"]); + } + + if (status2 !== AuthenticationStatus.Unlocked) { + await this.hideUi(); + throw new Error("Vault is not unlocked"); + } } } async informCredentialNotFound(): Promise { - this.logService.warning("informCredentialNotFound"); + this.logService.debug("informCredentialNotFound"); } async close() { - this.logService.warning("close"); + this.logService.debug("close"); } } diff --git a/apps/desktop/src/locales/en/messages.json b/apps/desktop/src/locales/en/messages.json index 70242b6674f..6e4a42bed5e 100644 --- a/apps/desktop/src/locales/en/messages.json +++ b/apps/desktop/src/locales/en/messages.json @@ -905,6 +905,12 @@ "unexpectedError": { "message": "An unexpected error has occurred." }, + "unexpectedErrorShort": { + "message": "Unexpected error" + }, + "closeThisBitwardenWindow": { + "message": "Close this Bitwarden window and try again." + }, "itemInformation": { "message": "Item information" }, @@ -3324,7 +3330,7 @@ "orgTrustWarning1": { "message": "This organization has an Enterprise policy that will enroll you in account recovery. Enrollment will allow organization administrators to change your password. Only proceed if you recognize this organization and the fingerprint phrase displayed below matches the organization's fingerprint." }, - "trustUser":{ + "trustUser": { "message": "Trust user" }, "inputRequired": { @@ -3854,6 +3860,75 @@ "fileSavedToDevice": { "message": "File saved to device. Manage from your device downloads." }, + "importantNotice": { + "message": "Important notice" + }, + "setupTwoStepLogin": { + "message": "Set up two-step login" + }, + "newDeviceVerificationNoticeContentPage1": { + "message": "Bitwarden will send a code to your account email to verify logins from new devices starting in February 2025." + }, + "newDeviceVerificationNoticeContentPage2": { + "message": "You can set up two-step login as an alternative way to protect your account or change your email to one you can access." + }, + "remindMeLater": { + "message": "Remind me later" + }, + "newDeviceVerificationNoticePageOneFormContent": { + "message": "Do you have reliable access to your email, $EMAIL$?", + "placeholders": { + "email": { + "content": "$1", + "example": "your_name@email.com" + } + } + }, + "newDeviceVerificationNoticePageOneEmailAccessNo": { + "message": "No, I do not" + }, + "newDeviceVerificationNoticePageOneEmailAccessYes": { + "message": "Yes, I can reliably access my email" + }, + "turnOnTwoStepLogin": { + "message": "Turn on two-step login" + }, + "changeAcctEmail": { + "message": "Change account email" + }, + "passkeyLogin": { + "message": "Log in with passkey?" + }, + "savePasskeyQuestion": { + "message": "Save passkey?" + }, + "saveNewPasskey": { + "message": "Save as new login" + }, + "savePasskeyNewLogin": { + "message": "Save passkey as new login" + }, + "noMatchingLoginsForSite": { + "message": "No matching logins for this site" + }, + "overwritePasskey": { + "message": "Overwrite passkey?" + }, + "unableToSavePasskey": { + "message": "Unable to save passkey" + }, + "alreadyContainsPasskey": { + "message": "This item already contains a passkey. Are you sure you want to overwrite the current passkey?" + }, + "passkeyAlreadyExists": { + "message": "A passkey already exists for this application." + }, + "applicationDoesNotSupportDuplicates": { + "message": "This application does not support duplicates." + }, + "closeThisWindow": { + "message": "Close this window" + }, "allowScreenshots": { "message": "Allow screen capture" }, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index fbb83a1bf56..76923b2db37 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -130,6 +130,8 @@ export class Main { } this.logService = new ElectronLogMainService(null, app.getPath("userData")); + this.logService.info("IS THIS THING ON?"); + this.logService.debug("IS THIS THING ON? [debug]"); const storageDefaults: any = {}; this.storageService = new ElectronStorageService(app.getPath("userData"), storageDefaults); @@ -304,7 +306,10 @@ export class Main { new ChromiumImporterService(); this.nativeAutofillMain = new NativeAutofillMain(this.logService, this.windowMain); - void this.nativeAutofillMain.init(); + void app.whenReady().then(async () => { + this.logService.debug("ATTEMPTING TO INITIALIZE NATIVE AUTOFILL"); + await this.nativeAutofillMain.init(); + }); this.mainDesktopAutotypeService = new MainDesktopAutotypeService( this.logService, diff --git a/apps/desktop/src/main/tray.main.ts b/apps/desktop/src/main/tray.main.ts index b7ddefe6e1b..81df6497ca8 100644 --- a/apps/desktop/src/main/tray.main.ts +++ b/apps/desktop/src/main/tray.main.ts @@ -53,9 +53,14 @@ export class TrayMain { }, { visible: isDev(), - label: "Fake Popup", + label: "Fake Popup Select", click: () => this.fakePopup(), }, + { + visible: isDev(), + label: "Fake Popup Create", + click: () => this.fakePopupCreate(), + }, { type: "separator" }, { label: this.i18nService.t("exit"), @@ -218,4 +223,8 @@ export class TrayMain { private async fakePopup() { await this.messagingService.send("loadurl", { url: "/passkeys", modal: true }); } + + private async fakePopupCreate() { + await this.messagingService.send("loadurl", { url: "/create-passkey", modal: true }); + } } diff --git a/apps/desktop/src/main/window.main.ts b/apps/desktop/src/main/window.main.ts index f8ea7551c47..8de60fce568 100644 --- a/apps/desktop/src/main/window.main.ts +++ b/apps/desktop/src/main/window.main.ts @@ -100,10 +100,10 @@ export class WindowMain { applyMainWindowStyles(this.win, this.windowStates[mainWindowSizeKey]); // Because modal is used in front of another app, UX wise it makes sense to hide the main window when leaving modal mode. this.win.hide(); - } else if (!lastValue.isModalModeActive && newValue.isModalModeActive) { + } else if (newValue.isModalModeActive) { // Apply the popup modal styles this.logService.info("Applying popup modal styles", newValue.modalPosition); - applyPopupModalStyles(this.win, newValue.modalPosition); + applyPopupModalStyles(this.win, newValue.showTrafficButtons, newValue.modalPosition); this.win.show(); } }), @@ -272,7 +272,7 @@ export class WindowMain { this.win = new BrowserWindow({ width: this.windowStates[mainWindowSizeKey].width, height: this.windowStates[mainWindowSizeKey].height, - minWidth: 680, + minWidth: 600, minHeight: 500, x: this.windowStates[mainWindowSizeKey].x, y: this.windowStates[mainWindowSizeKey].y, diff --git a/apps/desktop/src/platform/main/autofill/native-autofill.main.ts b/apps/desktop/src/platform/main/autofill/native-autofill.main.ts index 71cfcab84ba..f1a6dca1792 100644 --- a/apps/desktop/src/platform/main/autofill/native-autofill.main.ts +++ b/apps/desktop/src/platform/main/autofill/native-autofill.main.ts @@ -1,12 +1,17 @@ import { ipcMain } from "electron"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; -import { autofill } from "@bitwarden/desktop-napi"; +import { autofill, passkey_authenticator } from "@bitwarden/desktop-napi"; import { WindowMain } from "../../../main/window.main"; import { CommandDefinition } from "./command"; +type BufferedMessage = { + channel: string; + data: any; +}; + export type RunCommandParams = { namespace: C["namespace"]; command: C["name"]; @@ -17,13 +22,56 @@ export type RunCommandResult = C["output"]; export class NativeAutofillMain { private ipcServer: autofill.IpcServer | null; + private messageBuffer: BufferedMessage[] = []; + private listenerReady = false; constructor( private logService: LogService, private windowMain: WindowMain, ) {} + /** + * Safely sends a message to the renderer, buffering it if the server isn't ready yet + */ + private safeSend(channel: string, data: any) { + if (this.listenerReady && this.windowMain.win?.webContents) { + this.windowMain.win.webContents.send(channel, data); + } else { + this.messageBuffer.push({ channel, data }); + } + } + + /** + * Flushes all buffered messages to the renderer + */ + private flushMessageBuffer() { + if (!this.windowMain.win?.webContents) { + this.logService.error("Cannot flush message buffer - window not available"); + return; + } + + this.logService.info(`Flushing ${this.messageBuffer.length} buffered messages`); + + for (const { channel, data } of this.messageBuffer) { + this.windowMain.win.webContents.send(channel, data); + } + + this.messageBuffer = []; + } + async init() { + if (process.platform === "win32") { + try { + passkey_authenticator.register(); + } catch (err) { + this.logService.error("Failed to register windows passkey plugin:", err); + return JSON.stringify({ + type: "error", + message: "Failed to register windows passkey plugin", + }); + } + } + ipcMain.handle( "autofill.runCommand", ( @@ -43,7 +91,7 @@ export class NativeAutofillMain { this.ipcServer.completeError(clientId, sequenceNumber, String(error)); return; } - this.windowMain.win.webContents.send("autofill.passkeyRegistration", { + this.safeSend("autofill.passkeyRegistration", { clientId, sequenceNumber, request, @@ -56,7 +104,7 @@ export class NativeAutofillMain { this.ipcServer.completeError(clientId, sequenceNumber, String(error)); return; } - this.windowMain.win.webContents.send("autofill.passkeyAssertion", { + this.safeSend("autofill.passkeyAssertion", { clientId, sequenceNumber, request, @@ -69,28 +117,49 @@ export class NativeAutofillMain { this.ipcServer.completeError(clientId, sequenceNumber, String(error)); return; } - this.windowMain.win.webContents.send("autofill.passkeyAssertionWithoutUserInterface", { + this.safeSend("autofill.passkeyAssertionWithoutUserInterface", { clientId, sequenceNumber, request, }); }, + // NativeStatusCallback + (error, clientId, sequenceNumber, status) => { + if (error) { + this.logService.error("autofill.IpcServer.nativeStatus", error); + this.ipcServer.completeError(clientId, sequenceNumber, String(error)); + return; + } + this.safeSend("autofill.nativeStatus", { + clientId, + sequenceNumber, + status, + }); + }, ); + ipcMain.on("autofill.listenerReady", () => { + this.listenerReady = true; + this.logService.info( + `Listener is ready, flushing ${this.messageBuffer.length} buffered messages`, + ); + this.flushMessageBuffer(); + }); + ipcMain.on("autofill.completePasskeyRegistration", (event, data) => { - this.logService.warning("autofill.completePasskeyRegistration", data); + this.logService.debug("autofill.completePasskeyRegistration", data); const { clientId, sequenceNumber, response } = data; this.ipcServer.completeRegistration(clientId, sequenceNumber, response); }); ipcMain.on("autofill.completePasskeyAssertion", (event, data) => { - this.logService.warning("autofill.completePasskeyAssertion", data); + this.logService.debug("autofill.completePasskeyAssertion", data); const { clientId, sequenceNumber, response } = data; this.ipcServer.completeAssertion(clientId, sequenceNumber, response); }); ipcMain.on("autofill.completeError", (event, data) => { - this.logService.warning("autofill.completeError", data); + this.logService.debug("autofill.completeError", data); const { clientId, sequenceNumber, error } = data; this.ipcServer.completeError(clientId, sequenceNumber, String(error)); }); diff --git a/apps/desktop/src/platform/models/domain/window-state.ts b/apps/desktop/src/platform/models/domain/window-state.ts index 0efc9a1efab..ab52531bb5d 100644 --- a/apps/desktop/src/platform/models/domain/window-state.ts +++ b/apps/desktop/src/platform/models/domain/window-state.ts @@ -14,5 +14,6 @@ export class WindowState { export class ModalModeState { isModalModeActive: boolean; + showTrafficButtons?: boolean; modalPosition?: { x: number; y: number }; // Modal position is often passed from the native UI } diff --git a/apps/desktop/src/platform/popup-modal-styles.ts b/apps/desktop/src/platform/popup-modal-styles.ts index ae46ebb5c76..e1d3bb566f5 100644 --- a/apps/desktop/src/platform/popup-modal-styles.ts +++ b/apps/desktop/src/platform/popup-modal-styles.ts @@ -3,15 +3,19 @@ import { BrowserWindow } from "electron"; import { WindowState } from "./models/domain/window-state"; // change as needed, however limited by mainwindow minimum size -const popupWidth = 680; -const popupHeight = 500; +const popupWidth = 600; +const popupHeight = 600; type Position = { x: number; y: number }; -export function applyPopupModalStyles(window: BrowserWindow, position?: Position) { +export function applyPopupModalStyles( + window: BrowserWindow, + showTrafficButtons: boolean = true, + position?: Position, +) { window.unmaximize(); window.setSize(popupWidth, popupHeight); - window.setWindowButtonVisibility?.(false); + window.setWindowButtonVisibility?.(showTrafficButtons); window.setMenuBarVisibility?.(false); window.setResizable(false); window.setAlwaysOnTop(true); @@ -40,7 +44,7 @@ function positionWindow(window: BrowserWindow, position?: Position) { } export function applyMainWindowStyles(window: BrowserWindow, existingWindowState: WindowState) { - window.setMinimumSize(680, 500); + window.setMinimumSize(popupWidth, popupHeight); // need to guard against null/undefined values diff --git a/apps/desktop/src/platform/services/desktop-settings.service.ts b/apps/desktop/src/platform/services/desktop-settings.service.ts index c11f10646d7..d7c17433471 100644 --- a/apps/desktop/src/platform/services/desktop-settings.service.ts +++ b/apps/desktop/src/platform/services/desktop-settings.service.ts @@ -335,9 +335,14 @@ export class DesktopSettingsService { * Sets the modal mode of the application. Setting this changes the windows-size and other properties. * @param value `true` if the application is in modal mode, `false` if it is not. */ - async setModalMode(value: boolean, modalPosition?: { x: number; y: number }) { + async setModalMode( + value: boolean, + showTrafficButtons?: boolean, + modalPosition?: { x: number; y: number }, + ) { await this.modalModeState.update(() => ({ isModalModeActive: value, + showTrafficButtons, modalPosition, })); } diff --git a/apps/desktop/src/platform/services/electron-log.main.service.ts b/apps/desktop/src/platform/services/electron-log.main.service.ts index 947f4449271..2d5070527ab 100644 --- a/apps/desktop/src/platform/services/electron-log.main.service.ts +++ b/apps/desktop/src/platform/services/electron-log.main.service.ts @@ -22,7 +22,7 @@ export class ElectronLogMainService extends BaseLogService { return; } - log.transports.file.level = "info"; + log.transports.file.level = "debug"; if (this.logDir != null) { log.transports.file.resolvePathFn = () => path.join(this.logDir, "app.log"); } diff --git a/build.sh b/build.sh new file mode 100644 index 00000000000..9ade3d41a93 --- /dev/null +++ b/build.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +cd apps/desktop/desktop_native/napi +npm run build +cd ../.. +npm run build && npm run pack:win +cd ../.. + diff --git a/eslint.config.mjs b/eslint.config.mjs index 6c362a4dc43..54117b53e4e 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -196,7 +196,7 @@ export default tseslint.config( { // uses negative lookahead to whitelist any class that doesn't start with "tw-" // in other words: classnames that start with tw- must be valid TailwindCSS classes - whitelist: ["(?!(tw)\\-).*"], + whitelist: ["(?!(tw)\\-).*", "tw-app-region-drag", "tw-app-region-no-drag"], }, ], "tailwindcss/enforces-negative-arbitrary-values": "error", @@ -348,6 +348,7 @@ export default tseslint.config( "file-selector", "mfaType.*", "filter.*", // Temporary until filters are migrated + "tw-app-region*", // Custom utility for native passkey modals "tw-@container", ], }, diff --git a/libs/common/spec/fake-account-service.ts b/libs/common/spec/fake-account-service.ts index ba48181faa2..389975dc2e1 100644 --- a/libs/common/spec/fake-account-service.ts +++ b/libs/common/spec/fake-account-service.ts @@ -37,6 +37,8 @@ export class FakeAccountService implements AccountService { accountActivitySubject = new ReplaySubject>(1); // eslint-disable-next-line rxjs/no-exposed-subjects -- test class accountVerifyDevicesSubject = new ReplaySubject(1); + // eslint-disable-next-line rxjs/no-exposed-subjects -- test class + showHeaderSubject = new ReplaySubject(1); private _activeUserId: UserId; get activeUserId() { return this._activeUserId; @@ -55,6 +57,7 @@ export class FakeAccountService implements AccountService { }), ); } + showHeader$ = this.showHeaderSubject.asObservable(); get nextUpAccount$(): Observable { return combineLatest([this.accounts$, this.activeAccount$, this.sortedUserIds$]).pipe( map(([accounts, activeAccount, sortedUserIds]) => { @@ -114,6 +117,10 @@ export class FakeAccountService implements AccountService { this.accountsSubject.next(updated); await this.mock.clean(userId); } + + async setShowHeader(value: boolean): Promise { + this.showHeaderSubject.next(value); + } } const loggedOutInfo: AccountInfo = { diff --git a/libs/common/src/auth/abstractions/account.service.ts b/libs/common/src/auth/abstractions/account.service.ts index a3dabeecf8a..8b0280feb01 100644 --- a/libs/common/src/auth/abstractions/account.service.ts +++ b/libs/common/src/auth/abstractions/account.service.ts @@ -47,6 +47,8 @@ export abstract class AccountService { abstract sortedUserIds$: Observable; /** Next account that is not the current active account */ abstract nextUpAccount$: Observable; + /** Observable to display the header */ + abstract showHeader$: Observable; /** * Updates the `accounts$` observable with the new account data. * @@ -100,6 +102,11 @@ export abstract class AccountService { * @param lastActivity */ abstract setAccountActivity(userId: UserId, lastActivity: Date): Promise; + /** + * Show the account switcher. + * @param value + */ + abstract setShowHeader(visible: boolean): Promise; } export abstract class InternalAccountService extends AccountService { diff --git a/libs/common/src/auth/services/account.service.spec.ts b/libs/common/src/auth/services/account.service.spec.ts index 3fc47002083..3e3c878eaac 100644 --- a/libs/common/src/auth/services/account.service.spec.ts +++ b/libs/common/src/auth/services/account.service.spec.ts @@ -429,6 +429,16 @@ describe("accountService", () => { }, ); }); + + describe("setShowHeader", () => { + it("should update _showHeader$ when setShowHeader is called", async () => { + expect(sut["_showHeader$"].value).toBe(true); + + await sut.setShowHeader(false); + + expect(sut["_showHeader$"].value).toBe(false); + }); + }); }); }); diff --git a/libs/common/src/auth/services/account.service.ts b/libs/common/src/auth/services/account.service.ts index 1be11b03461..fb4b590ce77 100644 --- a/libs/common/src/auth/services/account.service.ts +++ b/libs/common/src/auth/services/account.service.ts @@ -6,6 +6,7 @@ import { distinctUntilChanged, shareReplay, combineLatest, + BehaviorSubject, Observable, switchMap, filter, @@ -84,6 +85,7 @@ export const getOptionalUserId = map( export class AccountServiceImplementation implements InternalAccountService { private accountsState: GlobalState>; private activeAccountIdState: GlobalState; + private _showHeader$ = new BehaviorSubject(true); accounts$: Observable>; activeAccount$: Observable; @@ -91,6 +93,7 @@ export class AccountServiceImplementation implements InternalAccountService { accountVerifyNewDeviceLogin$: Observable; sortedUserIds$: Observable; nextUpAccount$: Observable; + showHeader$ = this._showHeader$.asObservable(); constructor( private messagingService: MessagingService, @@ -262,6 +265,10 @@ export class AccountServiceImplementation implements InternalAccountService { } } + async setShowHeader(visible: boolean): Promise { + this._showHeader$.next(visible); + } + private async setAccountInfo(userId: UserId, update: Partial): Promise { function newAccountInfo(oldAccountInfo: AccountInfo): AccountInfo { return { ...oldAccountInfo, ...update }; diff --git a/libs/common/src/enums/feature-flag.enum.ts b/libs/common/src/enums/feature-flag.enum.ts index bfb40aff106..07e0874f1fa 100644 --- a/libs/common/src/enums/feature-flag.enum.ts +++ b/libs/common/src/enums/feature-flag.enum.ts @@ -19,6 +19,7 @@ export enum FeatureFlag { /* Autofill */ MacOsNativeCredentialSync = "macos-native-credential-sync", + WindowsNativeCredentialSync = "windows-native-credential-sync", WindowsDesktopAutotype = "windows-desktop-autotype", /* Billing */ @@ -86,6 +87,7 @@ export const DefaultFeatureFlagValue = { /* Autofill */ [FeatureFlag.MacOsNativeCredentialSync]: FALSE, + [FeatureFlag.WindowsNativeCredentialSync]: true, [FeatureFlag.WindowsDesktopAutotype]: FALSE, /* Tools */ diff --git a/libs/common/src/platform/abstractions/fido2/fido2-authenticator.service.abstraction.ts b/libs/common/src/platform/abstractions/fido2/fido2-authenticator.service.abstraction.ts index c34c4b835cf..427266522e9 100644 --- a/libs/common/src/platform/abstractions/fido2/fido2-authenticator.service.abstraction.ts +++ b/libs/common/src/platform/abstractions/fido2/fido2-authenticator.service.abstraction.ts @@ -138,7 +138,7 @@ export interface Fido2AuthenticatorGetAssertionParams { rpId: string; /** The hash of the serialized client data, provided by the client. */ hash: BufferSource; - allowCredentialDescriptorList: PublicKeyCredentialDescriptor[]; + allowCredentialDescriptorList?: PublicKeyCredentialDescriptor[]; /** The effective user verification requirement for assertion, a Boolean value provided by the client. */ requireUserVerification: boolean; /** The constant Boolean value true. It is included here as a pseudo-parameter to simplify applying this abstract authenticator model to implementations that may wish to make a test of user presence optional although WebAuthn does not. */ diff --git a/libs/common/src/platform/abstractions/fido2/fido2-user-interface.service.abstraction.ts b/libs/common/src/platform/abstractions/fido2/fido2-user-interface.service.abstraction.ts index 28b199da78f..b8be164c837 100644 --- a/libs/common/src/platform/abstractions/fido2/fido2-user-interface.service.abstraction.ts +++ b/libs/common/src/platform/abstractions/fido2/fido2-user-interface.service.abstraction.ts @@ -95,7 +95,7 @@ export abstract class Fido2UserInterfaceSession { */ abstract confirmNewCredential( params: NewCredentialParams, - ): Promise<{ cipherId: string; userVerified: boolean }>; + ): Promise<{ cipherId?: string; userVerified: boolean }>; /** * Make sure that the vault is unlocked. diff --git a/libs/common/src/platform/services/fido2/fido2-authenticator.service.ts b/libs/common/src/platform/services/fido2/fido2-authenticator.service.ts index e560a77cc2e..c64e8ecf5e2 100644 --- a/libs/common/src/platform/services/fido2/fido2-authenticator.service.ts +++ b/libs/common/src/platform/services/fido2/fido2-authenticator.service.ts @@ -128,6 +128,7 @@ export class Fido2AuthenticatorService let userVerified = false; let credentialId: string; let pubKeyDer: ArrayBuffer; + const response = await userInterfaceSession.confirmNewCredential({ credentialName: params.rpEntity.name, userName: params.userEntity.name, @@ -189,7 +190,7 @@ export class Fido2AuthenticatorService } const reencrypted = await this.cipherService.encrypt(cipher, activeUserId); await this.cipherService.updateWithServer(reencrypted); - await this.cipherService.clearCache(activeUserId); + // await this.cipherService.clearCache(activeUserId); credentialId = fido2Credential.credentialId; } catch (error) { this.logService?.error( @@ -457,8 +458,10 @@ export class Fido2AuthenticatorService } private async findCredentialsByRp(rpId: string): Promise { + this.logService.debug("[findCredentialByRp]:", rpId); const activeUserId = await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId)); const ciphers = await this.cipherService.getAllDecrypted(activeUserId); + this.logService.debug("[findCredentialsByRp] ciphers:", ciphers); return ciphers.filter( (cipher) => !cipher.isDeleted && diff --git a/libs/common/src/platform/services/fido2/fido2-utils.spec.ts b/libs/common/src/platform/services/fido2/fido2-utils.spec.ts index 9bb4ed0a4c5..6b34f772798 100644 --- a/libs/common/src/platform/services/fido2/fido2-utils.spec.ts +++ b/libs/common/src/platform/services/fido2/fido2-utils.spec.ts @@ -1,3 +1,9 @@ +import { mock } from "jest-mock-extended"; + +import { CipherType } from "@bitwarden/common/vault/enums"; +import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { Fido2CredentialView } from "@bitwarden/common/vault/models/view/fido2-credential.view"; + import { Fido2Utils } from "./fido2-utils"; describe("Fido2 Utils", () => { @@ -67,4 +73,62 @@ describe("Fido2 Utils", () => { expect(expectedArray).toBeNull(); }); }); + + describe("cipherHasNoOtherPasskeys(...)", () => { + const emptyPasskeyCipher = mock({ + id: "id-5", + localData: { lastUsedDate: 222 }, + name: "name-5", + type: CipherType.Login, + login: { + username: "username-5", + password: "password", + uri: "https://example.com", + fido2Credentials: [], + }, + }); + + const passkeyCipher = mock({ + id: "id-5", + localData: { lastUsedDate: 222 }, + name: "name-5", + type: CipherType.Login, + login: { + username: "username-5", + password: "password", + uri: "https://example.com", + fido2Credentials: [ + mock({ + credentialId: "credential-id", + rpName: "credential-name", + userHandle: "user-handle-1", + userName: "credential-username", + rpId: "jest-testing-website.com", + }), + mock({ + credentialId: "credential-id", + rpName: "credential-name", + userHandle: "user-handle-2", + userName: "credential-username", + rpId: "jest-testing-website.com", + }), + ], + }, + }); + + it("should return true when there is no userHandle", () => { + const userHandle = "user-handle-1"; + expect(Fido2Utils.cipherHasNoOtherPasskeys(emptyPasskeyCipher, userHandle)).toBeTruthy(); + }); + + it("should return true when userHandle matches", () => { + const userHandle = "user-handle-1"; + expect(Fido2Utils.cipherHasNoOtherPasskeys(passkeyCipher, userHandle)).toBeTruthy(); + }); + + it("should return false when userHandle doesn't match", () => { + const userHandle = "testing"; + expect(Fido2Utils.cipherHasNoOtherPasskeys(passkeyCipher, userHandle)).toBeFalsy(); + }); + }); }); diff --git a/libs/common/src/platform/services/fido2/fido2-utils.ts b/libs/common/src/platform/services/fido2/fido2-utils.ts index 99e260f4a53..8efd4734d81 100644 --- a/libs/common/src/platform/services/fido2/fido2-utils.ts +++ b/libs/common/src/platform/services/fido2/fido2-utils.ts @@ -1,3 +1,5 @@ +import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; + // FIXME: Update this file to be type safe and remove this and next line import type { AssertCredentialResult, @@ -111,4 +113,16 @@ export class Fido2Utils { return output; } + + /** + * This methods returns true if a cipher either has no passkeys, or has a passkey matching with userHandle + * @param userHandle + */ + static cipherHasNoOtherPasskeys(cipher: CipherView, userHandle: string): boolean { + if (cipher.login.fido2Credentials == null || cipher.login.fido2Credentials.length === 0) { + return true; + } + + return cipher.login.fido2Credentials.some((passkey) => passkey.userHandle === userHandle); + } } diff --git a/libs/common/src/platform/services/fido2/guid-utils.spec.ts b/libs/common/src/platform/services/fido2/guid-utils.spec.ts index 098ea4bee75..c58bd2720fa 100644 --- a/libs/common/src/platform/services/fido2/guid-utils.spec.ts +++ b/libs/common/src/platform/services/fido2/guid-utils.spec.ts @@ -1,28 +1,63 @@ -import { guidToRawFormat } from "./guid-utils"; +import { guidToRawFormat, guidToStandardFormat } from "./guid-utils"; + +const workingExamples: [string, Uint8Array][] = [ + [ + "00000000-0000-0000-0000-000000000000", + new Uint8Array([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, + ]), + ], + [ + "08d70b74-e9f5-4522-a425-e5dcd40107e7", + new Uint8Array([ + 0x08, 0xd7, 0x0b, 0x74, 0xe9, 0xf5, 0x45, 0x22, 0xa4, 0x25, 0xe5, 0xdc, 0xd4, 0x01, 0x07, + 0xe7, + ]), + ], +]; describe("guid-utils", () => { describe("guidToRawFormat", () => { + it.each(workingExamples)( + "returns UUID in binary format when given a valid UUID string", + (input, expected) => { + const result = guidToRawFormat(input); + + expect(result).toEqual(expected); + }, + ); + it.each([ - [ - "00000000-0000-0000-0000-000000000000", - [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, - ], - "08d70b74-e9f5-4522-a425-e5dcd40107e7", - [ - 0x08, 0xd7, 0x0b, 0x74, 0xe9, 0xf5, 0x45, 0x22, 0xa4, 0x25, 0xe5, 0xdc, 0xd4, 0x01, 0x07, - 0xe7, - ], - ], - ])("returns UUID in binary format when given a valid UUID string", (input, expected) => { - const result = guidToRawFormat(input); - - expect(result).toEqual(new Uint8Array(expected)); + "invalid", + "", + "", + "00000000-0000-0000-0000-0000000000000000", + "00000000-0000-0000-0000-000000", + ])("throws an error when given an invalid UUID string", (input) => { + expect(() => guidToRawFormat(input)).toThrow(TypeError); }); + }); - it("throws an error when given an invalid UUID string", () => { - expect(() => guidToRawFormat("invalid")).toThrow(TypeError); + describe("guidToStandardFormat", () => { + it.each(workingExamples)( + "returns UUID in standard format when given a valid UUID array buffer", + (expected, input) => { + const result = guidToStandardFormat(input); + + expect(result).toEqual(expected); + }, + ); + + it.each([ + new Uint8Array(), + new Uint8Array([]), + new Uint8Array([ + 0x08, 0xd7, 0x0b, 0x74, 0xe9, 0xf5, 0x45, 0x22, 0xa4, 0x25, 0xe5, 0xdc, 0xd4, 0x01, 0x07, + 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, + ]), + ])("throws an error when given an invalid UUID array buffer", (input) => { + expect(() => guidToStandardFormat(input)).toThrow(TypeError); }); }); }); diff --git a/libs/common/src/platform/services/fido2/guid-utils.ts b/libs/common/src/platform/services/fido2/guid-utils.ts index 66e6cbb1d7c..e72fe84e930 100644 --- a/libs/common/src/platform/services/fido2/guid-utils.ts +++ b/libs/common/src/platform/services/fido2/guid-utils.ts @@ -53,6 +53,10 @@ export function guidToRawFormat(guid: string) { /** Convert raw 16 byte array to standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID. */ export function guidToStandardFormat(bufferSource: BufferSource) { + if (bufferSource.byteLength !== 16) { + throw TypeError("BufferSource length is invalid"); + } + const arr = bufferSource instanceof ArrayBuffer ? new Uint8Array(bufferSource) diff --git a/libs/common/src/vault/abstractions/cipher.service.ts b/libs/common/src/vault/abstractions/cipher.service.ts index 9aefd960b2f..b95d9023a7c 100644 --- a/libs/common/src/vault/abstractions/cipher.service.ts +++ b/libs/common/src/vault/abstractions/cipher.service.ts @@ -68,6 +68,7 @@ export abstract class CipherService implements UserKeyRotationDataProvider; + abstract getAllDecryptedForIds(userId: UserId, ids: string[]): Promise; abstract filterCiphersForUrl( ciphers: C[], url: string, diff --git a/libs/common/src/vault/services/cipher.service.ts b/libs/common/src/vault/services/cipher.service.ts index 1e7e5302d41..20ac1cf0eb3 100644 --- a/libs/common/src/vault/services/cipher.service.ts +++ b/libs/common/src/vault/services/cipher.service.ts @@ -620,6 +620,15 @@ export class CipherService implements CipherServiceAbstraction { ); } + async getAllDecryptedForIds(userId: UserId, ids: string[]): Promise { + return firstValueFrom( + this.cipherViews$(userId).pipe( + filter((ciphers) => ciphers != null), + map((ciphers) => ciphers.filter((cipher) => ids.includes(cipher.id))), + ), + ); + } + async filterCiphersForUrl( ciphers: C[], url: string, diff --git a/libs/components/src/icon-button/index.ts b/libs/components/src/icon-button/index.ts index cc52f263252..b753e53c96a 100644 --- a/libs/components/src/icon-button/index.ts +++ b/libs/components/src/icon-button/index.ts @@ -1,2 +1,2 @@ export * from "./icon-button.module"; -export { BitIconButtonComponent } from "./icon-button.component"; +export * from "./icon-button.component"; diff --git a/libs/components/src/tw-theme.css b/libs/components/src/tw-theme.css index f8e02a7e668..f0e55ddd9e1 100644 --- a/libs/components/src/tw-theme.css +++ b/libs/components/src/tw-theme.css @@ -168,6 +168,18 @@ text-align: unset; } + /** + * tw-app-region-drag and tw-app-region-no-drag are used for Electron window dragging behavior + * These will replace direct -webkit-app-region usage as part of the migration to Tailwind CSS + */ + .tw-app-region-drag { + -webkit-app-region: drag; + } + + .tw-app-region-no-drag { + -webkit-app-region: no-drag; + } + /** * Bootstrap uses z-index: 1050 for modals, dialogs and drag-and-drop previews should appear above them. * When bootstrap is removed, test if these styles are still needed and that overlays display properly over other content. diff --git a/libs/key-management-ui/src/lock/components/lock.component.spec.ts b/libs/key-management-ui/src/lock/components/lock.component.spec.ts index 69f949fb843..e381f378ec6 100644 --- a/libs/key-management-ui/src/lock/components/lock.component.spec.ts +++ b/libs/key-management-ui/src/lock/components/lock.component.spec.ts @@ -2,7 +2,7 @@ import { DebugElement } from "@angular/core"; import { ComponentFixture, TestBed } from "@angular/core/testing"; import { FormBuilder, ReactiveFormsModule } from "@angular/forms"; import { By } from "@angular/platform-browser"; -import { Router } from "@angular/router"; +import { ActivatedRoute, Router } from "@angular/router"; import { mock } from "jest-mock-extended"; import { firstValueFrom, interval, map, of, takeWhile, timeout } from "rxjs"; import { ZXCVBNResult } from "zxcvbn"; @@ -92,6 +92,13 @@ describe("LockComponent", () => { const mockLockComponentService = mock(); const mockAnonLayoutWrapperDataService = mock(); const mockBroadcasterService = mock(); + const mockActivatedRoute = { + snapshot: { + paramMap: { + get: jest.fn().mockReturnValue(null), // return null for 'disable-redirect' param + }, + }, + }; const mockConfigService = mock(); beforeEach(async () => { @@ -150,6 +157,7 @@ describe("LockComponent", () => { { provide: LockComponentService, useValue: mockLockComponentService }, { provide: AnonLayoutWrapperDataService, useValue: mockAnonLayoutWrapperDataService }, { provide: BroadcasterService, useValue: mockBroadcasterService }, + { provide: ActivatedRoute, useValue: mockActivatedRoute }, { provide: ConfigService, useValue: mockConfigService }, ], }) @@ -465,6 +473,14 @@ describe("LockComponent", () => { component.clientType = clientType; mockLockComponentService.getPreviousUrl.mockReturnValue(null); + jest.spyOn(component as any, "doContinue").mockImplementation(async () => { + await mockBiometricStateService.resetUserPromptCancelled(); + mockMessagingService.send("unlocked"); + await mockSyncService.fullSync(false); + await mockUserAsymmetricKeysRegenerationService.regenerateIfNeeded(userId); + await mockRouter.navigate([navigateUrl]); + }); + await component.successfulMasterPasswordUnlock({ userKey: mockUserKey, masterPassword }); assertUnlocked(); @@ -476,6 +492,16 @@ describe("LockComponent", () => { component.shouldClosePopout = true; mockPlatformUtilsService.getDevice.mockReturnValue(DeviceType.FirefoxExtension); + jest.spyOn(component as any, "doContinue").mockImplementation(async () => { + await mockBiometricStateService.resetUserPromptCancelled(); + mockMessagingService.send("unlocked"); + await mockSyncService.fullSync(false); + await mockUserAsymmetricKeysRegenerationService.regenerateIfNeeded( + component.activeAccount!.id, + ); + mockLockComponentService.closeBrowserExtensionPopout(); + }); + await component.successfulMasterPasswordUnlock({ userKey: mockUserKey, masterPassword }); assertUnlocked(); @@ -610,6 +636,32 @@ describe("LockComponent", () => { ])( "should unlock and force set password change = %o when master password on login = %o and evaluated password against policy = %o and policy set during user verification by master password", async (forceSetPassword, masterPasswordPolicyOptions, evaluatedMasterPassword) => { + jest.spyOn(component as any, "doContinue").mockImplementation(async () => { + await mockBiometricStateService.resetUserPromptCancelled(); + mockMessagingService.send("unlocked"); + + if (masterPasswordPolicyOptions?.enforceOnLogin) { + const passwordStrengthResult = mockPasswordStrengthService.getPasswordStrength( + masterPassword, + component.activeAccount!.email, + ); + const evaluated = mockPolicyService.evaluateMasterPassword( + passwordStrengthResult.score, + masterPassword, + masterPasswordPolicyOptions, + ); + if (!evaluated) { + await mockMasterPasswordService.setForceSetPasswordReason( + ForceSetPasswordReason.WeakMasterPassword, + userId, + ); + } + } + + await mockSyncService.fullSync(false); + await mockUserAsymmetricKeysRegenerationService.regenerateIfNeeded(userId); + }); + mockUserVerificationService.verifyUserByMasterPassword.mockResolvedValue({ ...masterPasswordVerificationResponse, policyOptions: @@ -724,6 +776,14 @@ describe("LockComponent", () => { component.clientType = clientType; mockLockComponentService.getPreviousUrl.mockReturnValue(null); + jest.spyOn(component as any, "doContinue").mockImplementation(async () => { + await mockBiometricStateService.resetUserPromptCancelled(); + mockMessagingService.send("unlocked"); + await mockSyncService.fullSync(false); + await mockUserAsymmetricKeysRegenerationService.regenerateIfNeeded(userId); + await mockRouter.navigate([navigateUrl]); + }); + await component.unlockViaMasterPassword(); assertUnlocked(); @@ -735,6 +795,16 @@ describe("LockComponent", () => { component.shouldClosePopout = true; mockPlatformUtilsService.getDevice.mockReturnValue(DeviceType.FirefoxExtension); + jest.spyOn(component as any, "doContinue").mockImplementation(async () => { + await mockBiometricStateService.resetUserPromptCancelled(); + mockMessagingService.send("unlocked"); + await mockSyncService.fullSync(false); + await mockUserAsymmetricKeysRegenerationService.regenerateIfNeeded( + component.activeAccount!.id, + ); + mockLockComponentService.closeBrowserExtensionPopout(); + }); + await component.unlockViaMasterPassword(); assertUnlocked(); diff --git a/libs/key-management-ui/src/lock/components/lock.component.ts b/libs/key-management-ui/src/lock/components/lock.component.ts index 801a9d191f5..2573442d678 100644 --- a/libs/key-management-ui/src/lock/components/lock.component.ts +++ b/libs/key-management-ui/src/lock/components/lock.component.ts @@ -1,7 +1,7 @@ import { CommonModule } from "@angular/common"; import { Component, NgZone, OnDestroy, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from "@angular/forms"; -import { Router } from "@angular/router"; +import { Router, ActivatedRoute } from "@angular/router"; import { BehaviorSubject, filter, @@ -159,6 +159,7 @@ export class LockComponent implements OnInit, OnDestroy { private keyService: KeyService, private platformUtilsService: PlatformUtilsService, private router: Router, + private activatedRoute: ActivatedRoute, private dialogService: DialogService, private messagingService: MessagingService, private biometricStateService: BiometricStateService, @@ -697,7 +698,13 @@ export class LockComponent implements OnInit, OnDestroy { } // determine success route based on client type - if (this.clientType != null) { + // The disable-redirect parameter allows callers to prevent automatic navigation after unlock, + // useful when the lock component is used in contexts where custom post-unlock behavior is needed + // such as passkey modals. + if ( + this.clientType != null && + this.activatedRoute.snapshot.paramMap.get("disable-redirect") === null + ) { const successRoute = clientTypeToSuccessRouteRecord[this.clientType]; await this.router.navigate([successRoute]); } diff --git a/package-lock.json b/package-lock.json index da21f9ca730..e353a8ca0cc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5933,28 +5933,6 @@ "node": ">=16.4" } }, - "node_modules/@electron/windows-sign": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@electron/windows-sign/-/windows-sign-1.2.2.tgz", - "integrity": "sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==", - "dev": true, - "license": "BSD-2-Clause", - "optional": true, - "peer": true, - "dependencies": { - "cross-dirname": "^0.1.0", - "debug": "^4.3.4", - "fs-extra": "^11.1.1", - "minimist": "^1.2.8", - "postject": "^1.0.0-alpha.6" - }, - "bin": { - "electron-windows-sign": "bin/electron-windows-sign.js" - }, - "engines": { - "node": ">=14.14" - } - }, "node_modules/@emnapi/core": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.4.3.tgz", @@ -19548,15 +19526,6 @@ "integrity": "sha512-vQOuWmBgsgG1ovGeDi8m6Zeu1JaqH/JncrxKmaqMbv/LunyOQdLiQhPHtOsNlbUI05TocR5nod/Mbs3HYtr6sQ==", "license": "MIT" }, - "node_modules/cross-dirname": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz", - "integrity": "sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true - }, "node_modules/cross-env": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-10.1.0.tgz", @@ -34787,36 +34756,6 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", "license": "MIT" }, - "node_modules/postject": { - "version": "1.0.0-alpha.6", - "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz", - "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "commander": "^9.4.0" - }, - "bin": { - "postject": "dist/cli.js" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/postject/node_modules/commander": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", - "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "engines": { - "node": "^12.20.0 || >=14" - } - }, "node_modules/prebuild-install": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",