1
0
mirror of https://github.com/bitwarden/directory-connector synced 2026-02-25 00:52:53 +00:00

Compare commits

...

14 Commits

Author SHA1 Message Date
Jared
216f57a7f8 Merge branch 'main' into ac/pm-12436-replace-node-keytar-sonnet-attempt 2026-02-24 17:02:05 -05:00
JaredScar
3bf4916254 Refactor secure storage implementation to utilize the 'dc-native' module directly in the renderer process, removing the need for the credential storage listener. Update TypeScript definitions and enhance error handling in password management functions. Adjust Cargo dependencies and versions for improved compatibility. 2026-02-24 16:34:33 -05:00
JaredScar
8543265233 Refactor TypeScript definitions for password management functions by removing unnecessary semicolons. Update build scripts in package.json to exclude JavaScript during native module compilation. 2026-02-24 14:08:03 -05:00
JaredScar
9aab82dac6 Integrate native module 'dc-native' for secure storage, updating TypeScript configurations and package dependencies. Refactor native binding logic and enhance error handling. Remove legacy keytar references and adjust package-lock.json for new native module structure. 2026-02-24 11:56:12 -05:00
JaredScar
3abd3f0496 Refactor secure storage implementation to use native bindings and migrate from keytar. Update .gitignore for Rust artifacts, adjust package.json for new build scripts, and modify workflows for native module compilation. Enhance state versioning to support migration of credentials from keytar to desktop_core. 2026-02-24 11:42:16 -05:00
sven-bitwarden
984ae973a1 [PM-31004]: Fix Stackoverflow from Circular Group References (#991)
* Fix circular groups

* Simplify tests
2026-02-24 09:31:56 -06:00
renovate[bot]
af430157e0 [deps]: Update minimatch to v10 [SECURITY] - abandoned (#1009)
* [deps]: Update minimatch to v10 [SECURITY]

* Remove erroneous failing dependencies

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Sven <svernyi@bitwarden.com>
2026-02-23 13:10:23 -06:00
Jared
db3e7aa685 Refactor error handling in LdapDirectoryService to ensure proper unbinding and error propagation (#995) 2026-02-23 12:42:39 -05:00
Brandon Treston
9a2168c1d7 add lint workflow (#1006) 2026-02-19 11:43:39 -05:00
renovate[bot]
1fd8bf318f [deps]: Update webpack to v5.105.1 (#999)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-17 11:49:12 -05:00
renovate[bot]
c472d5e199 [deps]: Lock file maintenance (#1001)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Jared <TheWolfBadger@gmail.com>
2026-02-17 11:04:46 -05:00
renovate[bot]
1a42e76c79 [deps]: Update eslint-plugin-rxjs-x to v0.9.1 (#998)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-16 15:47:22 +00:00
Mick Letofsky
1aad9e1cbe Slim down and align with our current practices (#994) 2026-02-11 15:58:42 +01:00
Brandon Treston
3059934d4c remove substitute (#992) 2026-02-10 09:41:26 -05:00
38 changed files with 9184 additions and 2396 deletions

View File

@@ -9,26 +9,3 @@
## 📸 Screenshots
<!-- Required for any UI changes; delete if not applicable. Use fixed width images for better display. -->
## ⏰ Reminders before review
- Contributor guidelines followed
- All formatters and local linters executed and passed
- Written new unit and / or integration tests where applicable
- Used internationalization (i18n) for all UI strings
- CI builds passed
- Communicated to DevOps any deployment requirements
- Updated any necessary documentation (Confluence, contributing docs) or informed the documentation team
## 🦮 Reviewer guidelines
<!-- Suggested interactions but feel free to use (or not) as you desire! -->
- 👍 (`:+1:`) or similar for great changes
- 📝 (`:memo:`) or (`:information_source:`) for notes or general info
- ❓ (`:question:`) for questions
- 🤔 (`:thinking:`) or 💭 (`:thought_balloon:`) for more open inquiry that's not quite a confirmed issue and could potentially benefit from discussion
- 🎨 (`:art:`) for suggestions / improvements
- ❌ (`:x:`) or ⚠️ (`:warning:`) for more significant problems or concerns needing attention
- 🌱 (`:seedling:`) or ♻️ (`:recycle:`) for future improvements or indications of technical debt
- ⛏ (`:pick:`) for minor or nitpick changes

View File

@@ -62,31 +62,25 @@ jobs:
cache-dependency-path: '**/package-lock.json'
node-version: ${{ env._NODE_VERSION }}
- name: Update NPM
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
- name: Set up system dependencies
run: |
npm install -g node-gyp
node-gyp install "$(node -v)"
- name: Keytar
run: |
keytarVersion=$(cat package.json | jq -r '.dependencies.keytar')
keytarTar="keytar-v$keytarVersion-napi-v3-linux-x64.tar"
keytarTarGz="$keytarTar.gz"
keytarUrl="https://github.com/atom/node-keytar/releases/download/v$keytarVersion/$keytarTarGz"
mkdir -p ./keytar/linux
wget "$keytarUrl" -O "./keytar/linux/$keytarTarGz"
tar -xvf "./keytar/linux/$keytarTarGz" -C ./keytar/linux
sudo apt-get update
sudo apt-get -y install libdbus-1-dev libsecret-1-dev pkg-config
- name: Install
run: npm install
- name: Build native module
run: npm run build:native:release
- name: Package CLI
run: npm run dist:cli:lin
- name: Zip
run: zip -j "dist-cli/bwdc-linux-$_PACKAGE_VERSION.zip" "dist-cli/linux/bwdc" "keytar/linux/build/Release/keytar.node"
run: zip -j "dist-cli/bwdc-linux-$_PACKAGE_VERSION.zip" "dist-cli/linux/bwdc" "node_modules/dc-native/dc_native.linux-x64-gnu.node"
- name: Version Test
run: |
@@ -140,31 +134,20 @@ jobs:
cache-dependency-path: '**/package-lock.json'
node-version: ${{ env._NODE_VERSION }}
- name: Update NPM
run: |
npm install -g node-gyp
node-gyp install "$(node -v)"
- name: Keytar
run: |
keytarVersion=$(cat package.json | jq -r '.dependencies.keytar')
keytarTar="keytar-v$keytarVersion-napi-v3-darwin-x64.tar"
keytarTarGz="$keytarTar.gz"
keytarUrl="https://github.com/atom/node-keytar/releases/download/v$keytarVersion/$keytarTarGz"
mkdir -p ./keytar/macos
wget "$keytarUrl" -O "./keytar/macos/$keytarTarGz"
tar -xvf "./keytar/macos/$keytarTarGz" -C ./keytar/macos
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
- name: Install
run: npm install
- name: Build native module
run: npm run build:native:release
- name: Package CLI
run: npm run dist:cli:mac
- name: Zip
run: zip -j "dist-cli/bwdc-macos-$_PACKAGE_VERSION.zip" "dist-cli/macos/bwdc" "keytar/macos/build/Release/keytar.node"
run: zip -j "dist-cli/bwdc-macos-$_PACKAGE_VERSION.zip" "dist-cli/macos/bwdc" "node_modules/dc-native/dc_native.darwin-x64.node"
- name: Version Test
run: |
@@ -215,36 +198,23 @@ jobs:
cache-dependency-path: '**/package-lock.json'
node-version: ${{ env._NODE_VERSION }}
- name: Update NPM
run: |
npm install -g node-gyp
node-gyp install $(node -v)
- name: Keytar
shell: pwsh
run: |
$keytarVersion = (Get-Content -Raw -Path ./package.json | ConvertFrom-Json).dependencies.keytar
$keytarTar = "keytar-v${keytarVersion}-napi-v3-{0}-x64.tar"
$keytarTarGz = "${keytarTar}.gz"
$keytarUrl = "https://github.com/atom/node-keytar/releases/download/v${keytarVersion}/${keytarTarGz}"
New-Item -ItemType directory -Path ./keytar/windows | Out-Null
Invoke-RestMethod -Uri $($keytarUrl -f "win32") -OutFile "./keytar/windows/$($keytarTarGz -f "win32")"
7z e "./keytar/windows/$($keytarTarGz -f "win32")" -o"./keytar/windows"
7z e "./keytar/windows/$($keytarTar -f "win32")" -o"./keytar/windows"
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-pc-windows-msvc
- name: Install
run: npm install
- name: Build native module
run: npm run build:native:release
- name: Package CLI
run: npm run dist:cli:win
- name: Zip
shell: cmd
run: 7z a .\dist-cli\bwdc-windows-%_PACKAGE_VERSION%.zip .\dist-cli\windows\bwdc.exe .\keytar\windows\keytar.node
run: 7z a .\dist-cli\bwdc-windows-%_PACKAGE_VERSION%.zip .\dist-cli\windows\bwdc.exe .\node_modules\dc-native\dc_native.win32-x64-msvc.node
- name: Version Test
shell: pwsh
@@ -290,10 +260,10 @@ jobs:
cache-dependency-path: '**/package-lock.json'
node-version: ${{ env._NODE_VERSION }}
- name: Update NPM
run: |
npm install -g node-gyp
node-gyp install $(node -v)
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-pc-windows-msvc
- name: Print environment
run: |
@@ -390,15 +360,13 @@ jobs:
cache-dependency-path: '**/package-lock.json'
node-version: ${{ env._NODE_VERSION }}
- name: Update NPM
run: |
npm install -g node-gyp
node-gyp install "$(node -v)"
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
- name: Set up environment
run: |
sudo apt-get update
sudo apt-get -y install pkg-config libxss-dev libsecret-1-dev
sudo apt-get -y install pkg-config libxss-dev libsecret-1-dev libdbus-1-dev
sudo apt-get -y install rpm
- name: NPM Install
@@ -450,10 +418,8 @@ jobs:
cache-dependency-path: '**/package-lock.json'
node-version: ${{ env._NODE_VERSION }}
- name: Update NPM
run: |
npm install -g node-gyp
node-gyp install "$(node -v)"
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
- name: Print environment
run: |

46
.github/workflows/lint.yml vendored Normal file
View File

@@ -0,0 +1,46 @@
name: Lint
on:
workflow_dispatch:
push:
branches:
- "main"
- "rc"
- "hotfix-rc"
pull_request:
permissions:
contents: read
jobs:
lint:
name: Run linter
if: ${{ startsWith(github.head_ref, 'version_bump_') == false }}
runs-on: ubuntu-24.04
steps:
- name: Check out repo
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Get Node version
id: retrieve-node-version
run: |
NODE_NVMRC=$(cat .nvmrc)
NODE_VERSION=${NODE_NVMRC/v/''}
echo "node_version=$NODE_VERSION" >> "$GITHUB_OUTPUT"
- name: Set up Node
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
with:
cache: 'npm'
cache-dependency-path: '**/package-lock.json'
node-version: ${{ steps.retrieve-node-version.outputs.node_version }}
- name: Install Node dependencies
run: npm ci
- name: Run ESLint and Prettier
run: npm run lint

4
.gitignore vendored
View File

@@ -32,6 +32,10 @@ build
build-cli
.angular/cache
# Rust build artifacts
native/target
native/*.node
# Testing
coverage*
junit.xml*

2
.nvmrc
View File

@@ -1 +1 @@
v20
v22

View File

@@ -11,6 +11,7 @@
"app": "build"
},
"afterSign": "scripts/notarize.js",
"asarUnpack": ["node_modules/dc-native/*.node"],
"mac": {
"artifactName": "Bitwarden-Connector-${version}-mac.${ext}",
"category": "public.app-category.productivity",

View File

@@ -23,6 +23,7 @@ export default [
"eslint.config.mjs",
"scripts/**/*.js",
"**/node_modules/**",
"native/**",
],
},

View File

@@ -1,195 +0,0 @@
import { Substitute, Arg } from "@fluffy-spoon/substitute";
import { CryptoService } from "@/jslib/common/src/abstractions/crypto.service";
import { EncryptionType } from "@/jslib/common/src/enums/encryptionType";
import { EncString } from "@/jslib/common/src/models/domain/encString";
import { SymmetricCryptoKey } from "@/jslib/common/src/models/domain/symmetricCryptoKey";
import { ContainerService } from "@/jslib/common/src/services/container.service";
describe("EncString", () => {
afterEach(() => {
(window as any).bitwardenContainerService = undefined;
});
describe("Rsa2048_OaepSha256_B64", () => {
it("constructor", () => {
const encString = new EncString(EncryptionType.Rsa2048_OaepSha256_B64, "data");
expect(encString).toEqual({
data: "data",
encryptedString: "3.data",
encryptionType: 3,
});
});
describe("parse existing", () => {
it("valid", () => {
const encString = new EncString("3.data");
expect(encString).toEqual({
data: "data",
encryptedString: "3.data",
encryptionType: 3,
});
});
it("invalid", () => {
const encString = new EncString("3.data|test");
expect(encString).toEqual({
encryptedString: "3.data|test",
encryptionType: 3,
});
});
});
describe("decrypt", () => {
const encString = new EncString(EncryptionType.Rsa2048_OaepSha256_B64, "data");
const cryptoService = Substitute.for<CryptoService>();
cryptoService.getOrgKey(null).resolves(null);
cryptoService.decryptToUtf8(encString, Arg.any()).resolves("decrypted");
beforeEach(() => {
(window as any).bitwardenContainerService = new ContainerService(cryptoService);
});
it("decrypts correctly", async () => {
const decrypted = await encString.decrypt(null);
expect(decrypted).toBe("decrypted");
});
it("result should be cached", async () => {
const decrypted = await encString.decrypt(null);
cryptoService.received(1).decryptToUtf8(Arg.any(), Arg.any());
expect(decrypted).toBe("decrypted");
});
});
});
describe("AesCbc256_B64", () => {
it("constructor", () => {
const encString = new EncString(EncryptionType.AesCbc256_B64, "data", "iv");
expect(encString).toEqual({
data: "data",
encryptedString: "0.iv|data",
encryptionType: 0,
iv: "iv",
});
});
describe("parse existing", () => {
it("valid", () => {
const encString = new EncString("0.iv|data");
expect(encString).toEqual({
data: "data",
encryptedString: "0.iv|data",
encryptionType: 0,
iv: "iv",
});
});
it("invalid", () => {
const encString = new EncString("0.iv|data|mac");
expect(encString).toEqual({
encryptedString: "0.iv|data|mac",
encryptionType: 0,
});
});
});
});
describe("AesCbc256_HmacSha256_B64", () => {
it("constructor", () => {
const encString = new EncString(EncryptionType.AesCbc256_HmacSha256_B64, "data", "iv", "mac");
expect(encString).toEqual({
data: "data",
encryptedString: "2.iv|data|mac",
encryptionType: 2,
iv: "iv",
mac: "mac",
});
});
it("valid", () => {
const encString = new EncString("2.iv|data|mac");
expect(encString).toEqual({
data: "data",
encryptedString: "2.iv|data|mac",
encryptionType: 2,
iv: "iv",
mac: "mac",
});
});
it("invalid", () => {
const encString = new EncString("2.iv|data");
expect(encString).toEqual({
encryptedString: "2.iv|data",
encryptionType: 2,
});
});
});
it("Exit early if null", () => {
const encString = new EncString(null);
expect(encString).toEqual({
encryptedString: null,
});
});
describe("decrypt", () => {
it("throws exception when bitwarden container not initialized", async () => {
const encString = new EncString(null);
expect.assertions(1);
try {
await encString.decrypt(null);
} catch (e) {
expect(e.message).toEqual("global bitwardenContainerService not initialized.");
}
});
it("handles value it can't decrypt", async () => {
const encString = new EncString(null);
const cryptoService = Substitute.for<CryptoService>();
cryptoService.getOrgKey(null).resolves(null);
cryptoService.decryptToUtf8(encString, Arg.any()).throws("error");
(window as any).bitwardenContainerService = new ContainerService(cryptoService);
const decrypted = await encString.decrypt(null);
expect(decrypted).toBe("[error: cannot decrypt]");
expect(encString).toEqual({
decryptedValue: "[error: cannot decrypt]",
encryptedString: null,
});
});
it("passes along key", async () => {
const encString = new EncString(null);
const key = Substitute.for<SymmetricCryptoKey>();
const cryptoService = Substitute.for<CryptoService>();
cryptoService.getOrgKey(null).resolves(null);
(window as any).bitwardenContainerService = new ContainerService(cryptoService);
await encString.decrypt(null, key);
cryptoService.received().decryptToUtf8(encString, key);
});
});
});

View File

@@ -1,84 +0,0 @@
import { Arg, Substitute, SubstituteOf } from "@fluffy-spoon/substitute";
import { StorageService } from "@/jslib/common/src/abstractions/storage.service";
import { StateVersion } from "@/jslib/common/src/enums/stateVersion";
import { StateFactory } from "@/jslib/common/src/factories/stateFactory";
import { Account } from "@/jslib/common/src/models/domain/account";
import { GlobalState } from "@/jslib/common/src/models/domain/globalState";
import { StateMigrationService } from "@/jslib/common/src/services/stateMigration.service";
const userId = "USER_ID";
describe("State Migration Service", () => {
let storageService: SubstituteOf<StorageService>;
let secureStorageService: SubstituteOf<StorageService>;
let stateFactory: SubstituteOf<StateFactory>;
let stateMigrationService: StateMigrationService;
beforeEach(() => {
storageService = Substitute.for<StorageService>();
secureStorageService = Substitute.for<StorageService>();
stateFactory = Substitute.for<StateFactory>();
stateMigrationService = new StateMigrationService(
storageService,
secureStorageService,
stateFactory,
);
});
describe("StateVersion 3 to 4 migration", async () => {
beforeEach(() => {
const globalVersion3: Partial<GlobalState> = {
stateVersion: StateVersion.Three,
};
storageService.get("global", Arg.any()).resolves(globalVersion3);
storageService.get("authenticatedAccounts", Arg.any()).resolves([userId]);
});
it("clears everBeenUnlocked", async () => {
const accountVersion3: Account = {
profile: {
apiKeyClientId: null,
convertAccountToKeyConnector: null,
email: "EMAIL",
emailVerified: true,
everBeenUnlocked: true,
hasPremiumPersonally: false,
kdfIterations: 100000,
kdfType: 0,
keyHash: "KEY_HASH",
lastSync: "LAST_SYNC",
userId: userId,
usesKeyConnector: false,
forcePasswordReset: false,
},
};
const expectedAccountVersion4: Account = {
profile: {
...accountVersion3.profile,
},
};
delete expectedAccountVersion4.profile.everBeenUnlocked;
storageService.get(userId, Arg.any()).resolves(accountVersion3);
await stateMigrationService.migrate();
storageService.received(1).save(userId, expectedAccountVersion4, Arg.any());
});
it("updates StateVersion number", async () => {
await stateMigrationService.migrate();
storageService.received(1).save(
"global",
Arg.is((globals: GlobalState) => globals.stateVersion === StateVersion.Four),
Arg.any(),
);
});
});
});

View File

@@ -1,7 +1,3 @@
import { Substitute, Arg } from "@fluffy-spoon/substitute";
import { EncString } from "@/jslib/common/src/models/domain/encString";
function newGuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
@@ -21,13 +17,6 @@ export function BuildTestObject<T, K extends keyof T = keyof T>(
return Object.assign(constructor === null ? {} : new constructor(), def) as T;
}
export function mockEnc(s: string): EncString {
const mock = Substitute.for<EncString>();
mock.decrypt(Arg.any(), Arg.any()).resolves(s);
return mock;
}
export function makeStaticByteArray(length: number, start = 0) {
const arr = new Uint8Array(length);
for (let i = 0; i < length; i++) {

View File

@@ -3,5 +3,6 @@ export enum StateVersion {
Two = 2, // Move to a typed State object
Three = 3, // Fix migration of users' premium status
Four = 4, // Fix 'Never Lock' option by removing stale data
Latest = Four,
Five = 5, // Migrate Windows keychain credentials from keytar (UTF-8) to desktop_core (UTF-16)
Latest = Five,
}

View File

@@ -1,43 +1,53 @@
import { ipcRenderer } from "electron";
import { StorageService } from "@/jslib/common/src/abstractions/storage.service";
import { StorageOptions } from "@/jslib/common/src/models/domain/storageOptions";
import { passwords } from "dc-native";
const APPLICATION_NAME = "Bitwarden Directory Connector";
export class ElectronRendererSecureStorageService implements StorageService {
async get<T>(key: string, options?: StorageOptions): Promise<T> {
const val = ipcRenderer.sendSync("keytar", {
action: "getPassword",
key: key,
keySuffix: options?.keySuffix ?? "",
});
return Promise.resolve(val != null ? (JSON.parse(val) as T) : null);
return passwords
.getPassword(this.buildServiceName(options), key)
.then((val: string) => JSON.parse(val) as T)
.catch((e: Error): T => {
if (e.message === passwords.PASSWORD_NOT_FOUND) {
return null;
}
throw e;
});
}
async has(key: string, options?: StorageOptions): Promise<boolean> {
const val = ipcRenderer.sendSync("keytar", {
action: "hasPassword",
key: key,
keySuffix: options?.keySuffix ?? "",
});
return Promise.resolve(!!val);
return (await this.get(key, options)) != null;
}
async save(key: string, obj: any, options?: StorageOptions): Promise<any> {
ipcRenderer.sendSync("keytar", {
action: "setPassword",
key: key,
keySuffix: options?.keySuffix ?? "",
value: JSON.stringify(obj),
});
return Promise.resolve();
if (!obj) {
return this.remove(key, options);
}
return passwords.setPassword(
this.buildServiceName(options),
key,
JSON.stringify(obj),
);
}
async remove(key: string, options?: StorageOptions): Promise<any> {
ipcRenderer.sendSync("keytar", {
action: "deletePassword",
key: key,
keySuffix: options?.keySuffix ?? "",
return passwords.deletePassword(this.buildServiceName(options), key).catch((e: Error) => {
if (e.message === passwords.PASSWORD_NOT_FOUND) {
return;
}
throw e;
});
return Promise.resolve();
}
private buildServiceName(options?: StorageOptions): string {
const suffix = options?.keySuffix;
if (suffix) {
return `${APPLICATION_NAME}_${suffix}`;
}
return APPLICATION_NAME;
}
}

3504
native/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

27
native/Cargo.toml Normal file
View File

@@ -0,0 +1,27 @@
[package]
name = "dc_native"
version = "0.1.0"
edition = "2021"
description = "Native keychain bindings for Bitwarden Directory Connector"
license = "GPL-3.0"
[lib]
crate-type = ["cdylib"]
name = "dc_native"
[dependencies]
anyhow = "=1.0.100"
desktop_core = { git = "https://github.com/bitwarden/clients", rev = "00cf24972d944638bbd1adc00a0ae3eeabb6eb9a", package = "desktop_core" }
napi = { version = "2", features = ["async"] }
napi-derive = "2"
[target.'cfg(windows)'.dependencies]
scopeguard = "=1.2.0"
widestring = "=1.2.0"
windows = { version = "=0.61.1", features = [
"Win32_Foundation",
"Win32_Security_Credentials",
] }
[build-dependencies]
napi-build = "1"

5
native/build.rs Normal file
View File

@@ -0,0 +1,5 @@
extern crate napi_build;
fn main() {
napi_build::setup();
}

28
native/index.d.ts vendored Normal file
View File

@@ -0,0 +1,28 @@
/* auto-generated by NAPI-RS */
/* eslint-disable */
export declare namespace passwords {
/**
* Delete the stored password from the keychain.
* Throws an Error with message PASSWORD_NOT_FOUND if the password does not exist.
*/
export function deletePassword(service: string, account: string): Promise<void>;
/**
* Fetch the stored password from the keychain.
* Throws an Error with message PASSWORD_NOT_FOUND if the password does not exist.
*/
export function getPassword(service: string, account: string): Promise<string>;
/** Check if OS secure storage is available. */
export function isAvailable(): Promise<boolean>;
/**
* Migrate a credential that was stored by keytar (UTF-8 blob) to the new UTF-16 format
* used by desktop_core on Windows. No-ops on non-Windows platforms.
*
* Returns true if a migration was performed, false if the credential was already in the
* correct format or does not exist.
*/
export function migrateKeytarPassword(service: string, account: string): Promise<boolean>;
/** The error message returned when a password is not found during retrieval or deletion. */
export const PASSWORD_NOT_FOUND: string;
/** Save the password to the keychain. Adds an entry if none exists, otherwise updates it. */
export function setPassword(service: string, account: string, password: string): Promise<void>;
}

82
native/index.js Normal file
View File

@@ -0,0 +1,82 @@
const { existsSync } = require("fs");
const { join } = require("path");
const { platform, arch } = process;
let nativeBinding = null;
let loadError = null;
function loadFirstAvailable(localFiles) {
for (const localFile of localFiles) {
const filePath = join(__dirname, localFile);
if (existsSync(filePath)) {
return require(filePath);
}
}
throw new Error(
`Could not find dc-native binary for ${platform}-${arch}. Run 'npm run build:native' to compile it.`,
);
}
switch (platform) {
case "win32":
switch (arch) {
case "x64":
nativeBinding = loadFirstAvailable(["dc_native.win32-x64-msvc.node"]);
break;
case "arm64":
nativeBinding = loadFirstAvailable(["dc_native.win32-arm64-msvc.node"]);
break;
default:
throw new Error(`Unsupported architecture on Windows: ${arch}`);
}
break;
case "darwin":
switch (arch) {
case "x64":
nativeBinding = loadFirstAvailable(["dc_native.darwin-x64.node"]);
break;
case "arm64":
nativeBinding = loadFirstAvailable(["dc_native.darwin-arm64.node"]);
break;
default:
throw new Error(`Unsupported architecture on macOS: ${arch}`);
}
break;
case "linux":
switch (arch) {
case "x64":
nativeBinding = loadFirstAvailable(["dc_native.linux-x64-gnu.node"]);
break;
case "arm64":
nativeBinding = loadFirstAvailable(["dc_native.linux-arm64-gnu.node"]);
break;
default:
throw new Error(`Unsupported architecture on Linux: ${arch}`);
}
break;
default:
throw new Error(`Unsupported platform: ${platform}, architecture: ${arch}`);
}
if (!nativeBinding) {
if (loadError) {
throw loadError;
}
throw new Error(`Failed to load dc-native binding`);
}
// Re-export flat native symbols as the `passwords` namespace so all
// TypeScript callers (and the existing index.d.ts declarations) work unchanged.
module.exports = {
passwords: {
getPassword: (service, account) => nativeBinding.getPassword(service, account),
setPassword: (service, account, password) =>
nativeBinding.setPassword(service, account, password),
deletePassword: (service, account) => nativeBinding.deletePassword(service, account),
isAvailable: () => nativeBinding.isAvailable(),
migrateKeytarPassword: (service, account) =>
nativeBinding.migrateKeytarPassword(service, account),
PASSWORD_NOT_FOUND: "Password not found.",
},
};

1823
native/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

18
native/package.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "dc-native",
"version": "1.0.0",
"description": "Native keychain bindings for Bitwarden Directory Connector",
"main": "index.js",
"types": "index.d.ts",
"license": "GPL-3.0",
"napi": {
"binaryName": "dc_native"
},
"scripts": {
"build": "napi build --platform --no-js",
"build:release": "napi build --platform --release --no-js"
},
"devDependencies": {
"@napi-rs/cli": "^3.0.0"
}
}

64
native/src/lib.rs Normal file
View File

@@ -0,0 +1,64 @@
#[macro_use]
extern crate napi_derive;
/// Fetch the stored password from the keychain.
/// Throws an Error with message PASSWORD_NOT_FOUND if the password does not exist.
#[napi]
pub async fn get_password(service: String, account: String) -> napi::Result<String> {
desktop_core::password::get_password(&service, &account)
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
}
/// Save the password to the keychain. Adds an entry if none exists, otherwise updates it.
#[napi]
pub async fn set_password(
service: String,
account: String,
password: String,
) -> napi::Result<()> {
desktop_core::password::set_password(&service, &account, &password)
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
}
/// Delete the stored password from the keychain.
/// Throws an Error with message PASSWORD_NOT_FOUND if the password does not exist.
#[napi]
pub async fn delete_password(service: String, account: String) -> napi::Result<()> {
desktop_core::password::delete_password(&service, &account)
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
}
/// Check if OS secure storage is available.
#[napi]
pub async fn is_available() -> napi::Result<bool> {
desktop_core::password::is_available()
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
}
/// Migrate a credential that was stored by keytar (UTF-8 blob) to the new UTF-16 format
/// used by desktop_core on Windows. No-ops on non-Windows platforms.
///
/// Returns true if a migration was performed, false if the credential was already in the
/// correct format or does not exist.
#[napi]
pub async fn migrate_keytar_password(service: String, account: String) -> napi::Result<bool> {
#[cfg(windows)]
{
migration::migrate_keytar_password(&service, &account)
.await
.map_err(|e| napi::Error::from_reason(e.to_string()))
}
#[cfg(not(windows))]
{
let _ = (service, account);
Ok(false)
}
}
#[cfg(windows)]
mod migration;

67
native/src/migration.rs Normal file
View File

@@ -0,0 +1,67 @@
/// Windows-only: migrates credentials stored by keytar (UTF-8 blob via CredWriteA) to the
/// UTF-16 format expected by desktop_core (CredWriteW).
///
/// Keytar used CredWriteA on Windows, which stored the credential blob as raw UTF-8 bytes.
/// desktop_core uses CredWriteW with a UTF-16 encoded blob. Reading old keytar credentials
/// through desktop_core's get_password produces garbled output because the UTF-8 bytes are
/// reinterpreted as UTF-16.
///
/// This function detects the old format by checking whether the raw blob bytes are valid UTF-8
/// without null bytes (UTF-16 LE encoding of ASCII always contains null bytes). If so, it
/// re-saves the credential using desktop_core's set_password (UTF-16 encoding).
use anyhow::{anyhow, Result};
use widestring::U16CString;
use windows::{
core::PCWSTR,
Win32::Security::Credentials::{CredFree, CredReadW, CRED_TYPE_GENERIC},
};
pub async fn migrate_keytar_password(service: &str, account: &str) -> Result<bool> {
let target = format!("{}/{}", service, account);
let target_wide = U16CString::from_str(&target)?;
let mut credential = std::ptr::null_mut();
let result = unsafe {
CredReadW(
PCWSTR(target_wide.as_ptr()),
CRED_TYPE_GENERIC,
None,
&mut credential,
)
};
scopeguard::defer! {{
unsafe { CredFree(credential as *mut _) };
}};
if result.is_err() {
// Credential does not exist; nothing to migrate.
return Ok(false);
}
let blob_bytes: Vec<u8> = unsafe {
let blob_ptr = (*credential).CredentialBlob;
let blob_size = (*credential).CredentialBlobSize as usize;
if blob_ptr.is_null() || blob_size == 0 {
return Ok(false);
}
std::slice::from_raw_parts(blob_ptr, blob_size).to_vec()
};
// UTF-16 LE encoding of ASCII always contains null bytes (e.g. 'A' → 0x41 0x00).
// Keytar stored raw UTF-8 bytes which will never contain null bytes for valid JSON.
// If the blob is valid UTF-8 and contains no null bytes, it was written by keytar.
let blob_is_utf8 = std::str::from_utf8(&blob_bytes)
.map(|s| !s.contains('\0'))
.unwrap_or(false);
if !blob_is_utf8 {
// Already UTF-16 or unrecognised format; no migration needed.
return Ok(false);
}
let utf8_value = String::from_utf8(blob_bytes).map_err(|e| anyhow!(e))?;
desktop_core::password::set_password(service, account, &utf8_value).await?;
Ok(true)
}

4738
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -26,15 +26,16 @@
"symlink:win": "rm -rf ./jslib && cmd /c mklink /J .\\jslib ..\\jslib",
"symlink:mac": "npm run symlink:lin",
"symlink:lin": "rm -rf ./jslib && ln -s ../jslib ./jslib",
"rebuild": "electron-rebuild",
"reset": "rimraf --glob ./node_modules/keytar/* && npm install",
"build:native": "cd native && npm install && npm run build",
"build:native:release": "cd native && npm install && npm run build:release",
"rebuild": "npm run build:native:release",
"lint": "eslint . && prettier --check .",
"lint:fix": "eslint . --fix",
"build": "concurrently -n Main,Rend -c yellow,cyan \"npm run build:main\" \"npm run build:renderer\"",
"build:main": "webpack --config webpack.main.cjs",
"build:renderer": "webpack --config webpack.renderer.cjs",
"build:renderer:watch": "webpack --config webpack.renderer.cjs --watch",
"build:dist": "npm run reset && npm run rebuild && npm run build",
"build:dist": "npm run rebuild && npm run build",
"build:cli": "webpack --config webpack.cli.cjs",
"build:cli:watch": "webpack --config webpack.cli.cjs --watch",
"build:cli:prod": "cross-env NODE_ENV=production webpack --config webpack.cli.cjs",
@@ -78,8 +79,6 @@
"@angular/build": "21.1.2",
"@angular/compiler-cli": "21.1.1",
"@electron/notarize": "2.5.0",
"@electron/rebuild": "4.0.1",
"@fluffy-spoon/substitute": "1.208.0",
"@microsoft/microsoft-graph-types": "2.43.1",
"@ngtools/webpack": "21.1.2",
"@types/inquirer": "8.2.10",
@@ -95,7 +94,6 @@
"@typescript-eslint/parser": "8.54.0",
"@yao-pkg/pkg": "5.16.1",
"babel-loader": "10.0.0",
"clean-webpack-plugin": "4.0.0",
"jest-environment-jsdom": "30.2.0",
"concurrently": "9.2.0",
"copy-webpack-plugin": "13.0.0",
@@ -113,9 +111,9 @@
"eslint-import-resolver-typescript": "4.4.4",
"eslint-plugin-import": "2.32.0",
"eslint-plugin-rxjs-angular-x": "0.1.0",
"eslint-plugin-rxjs-x": "0.8.3",
"eslint-plugin-rxjs-x": "0.9.1",
"form-data": "4.0.4",
"glob": "13.0.0",
"glob": "13.0.6",
"html-loader": "5.1.0",
"html-webpack-plugin": "5.6.3",
"husky": "9.1.7",
@@ -125,7 +123,6 @@
"jest-preset-angular": "16.0.0",
"lint-staged": "16.2.6",
"mini-css-extract-plugin": "2.10.0",
"minimatch": "5.1.2",
"node-forge": "1.3.2",
"node-loader": "2.1.0",
"prettier": "3.8.1",
@@ -138,7 +135,7 @@
"tsconfig-paths-webpack-plugin": "4.2.0",
"type-fest": "5.4.2",
"typescript": "5.9.3",
"webpack": "5.104.1",
"webpack": "5.105.1",
"webpack-cli": "6.0.1",
"webpack-merge": "6.0.1",
"webpack-node-externals": "3.0.0",
@@ -165,7 +162,7 @@
"googleapis": "149.0.0",
"https-proxy-agent": "7.0.6",
"inquirer": "8.2.6",
"keytar": "7.9.0",
"dc-native": "file:./native",
"ldapts": "8.1.3",
"lowdb": "1.0.0",
"ngx-toastr": "20.0.4",
@@ -178,7 +175,7 @@
"zone.js": "0.16.0"
},
"engines": {
"node": "~20",
"node": "~22",
"npm": "~10"
},
"lint-staged": {

View File

@@ -24,8 +24,8 @@ import { AuthService } from "./services/auth.service";
import { BatchRequestBuilder } from "./services/batch-request-builder";
import { DefaultDirectoryFactoryService } from "./services/directory-factory.service";
import { I18nService } from "./services/i18n.service";
import { KeytarSecureStorageService } from "./services/keytarSecureStorage.service";
import { LowdbStorageService } from "./services/lowdbStorage.service";
import { NativeSecureStorageService } from "./services/nativeSecureStorage.service";
import { SingleRequestBuilder } from "./services/single-request-builder";
import { StateService } from "./services/state.service";
import { StateMigrationService } from "./services/stateMigration.service";
@@ -100,7 +100,7 @@ export class Main {
);
this.secureStorageService = plaintextSecrets
? this.storageService
: new KeytarSecureStorageService(applicationName);
: new NativeSecureStorageService(applicationName);
this.stateMigrationService = new StateMigrationService(
this.storageService,

View File

@@ -1,35 +1,11 @@
import { ipcMain } from "electron";
import { deletePassword, getPassword, setPassword } from "keytar";
// Secure storage is handled directly in the renderer process via dc-native,
// so this listener is no longer needed. Kept as a stub to avoid refactoring
// the main.ts bootstrap sequence.
export class DCCredentialStorageListener {
constructor(private serviceName: string) {}
init() {
ipcMain.on("keytar", async (event: any, message: any) => {
try {
let serviceName = this.serviceName;
message.keySuffix = "_" + (message.keySuffix ?? "");
if (message.keySuffix !== "_") {
serviceName += message.keySuffix;
}
let val: string | boolean = null;
if (message.action && message.key) {
if (message.action === "getPassword") {
val = await getPassword(serviceName, message.key);
} else if (message.action === "hasPassword") {
const result = await getPassword(serviceName, message.key);
val = result != null;
} else if (message.action === "setPassword" && message.value) {
await setPassword(serviceName, message.key, message.value);
} else if (message.action === "deletePassword") {
await deletePassword(serviceName, message.key);
}
}
event.returnValue = val;
} catch {
event.returnValue = null;
}
});
// no-op: renderer calls dc-native directly
}
}

View File

@@ -1,7 +1,8 @@
import { Arg, Substitute, SubstituteOf } from "@fluffy-spoon/substitute";
import { mock } from "jest-mock-extended";
import { ApiService } from "@/jslib/common/src/abstractions/api.service";
import { AppIdService } from "@/jslib/common/src/abstractions/appId.service";
import { MessagingService } from "@/jslib/common/src/abstractions/messaging.service";
import { PlatformUtilsService } from "@/jslib/common/src/abstractions/platformUtils.service";
import { Utils } from "@/jslib/common/src/misc/utils";
import {
@@ -11,7 +12,6 @@ import {
} from "@/jslib/common/src/models/domain/account";
import { IdentityTokenResponse } from "@/jslib/common/src/models/response/identityTokenResponse";
import { MessagingService } from "../../jslib/common/src/abstractions/messaging.service";
import { Account, DirectoryConfigurations, DirectorySettings } from "../models/account";
import { AuthService } from "./auth.service";
@@ -35,22 +35,22 @@ export function identityTokenResponseFactory() {
}
describe("AuthService", () => {
let apiService: SubstituteOf<ApiService>;
let appIdService: SubstituteOf<AppIdService>;
let platformUtilsService: SubstituteOf<PlatformUtilsService>;
let messagingService: SubstituteOf<MessagingService>;
let stateService: SubstituteOf<StateService>;
let apiService: jest.Mocked<ApiService>;
let appIdService: jest.Mocked<AppIdService>;
let platformUtilsService: jest.Mocked<PlatformUtilsService>;
let messagingService: jest.Mocked<MessagingService>;
let stateService: jest.Mocked<StateService>;
let authService: AuthService;
beforeEach(async () => {
apiService = Substitute.for();
appIdService = Substitute.for();
platformUtilsService = Substitute.for();
stateService = Substitute.for();
messagingService = Substitute.for();
apiService = mock<ApiService>();
appIdService = mock<AppIdService>();
platformUtilsService = mock<PlatformUtilsService>();
stateService = mock<StateService>();
messagingService = mock<MessagingService>();
appIdService.getAppId().resolves(deviceId);
appIdService.getAppId.mockResolvedValue(deviceId);
authService = new AuthService(
apiService,
@@ -62,11 +62,12 @@ describe("AuthService", () => {
});
it("sets the local environment after a successful login", async () => {
apiService.postIdentityToken(Arg.any()).resolves(identityTokenResponseFactory());
apiService.postIdentityToken.mockResolvedValue(identityTokenResponseFactory());
await authService.logIn({ clientId, clientSecret });
stateService.received(1).addAccount(
expect(stateService.addAccount).toHaveBeenCalledTimes(1);
expect(stateService.addAccount).toHaveBeenCalledWith(
new Account({
profile: {
...new AccountProfile(),

View File

@@ -68,10 +68,12 @@ export class LdapDirectoryService implements IDirectoryService {
}
groups = await this.getGroups(groupForce);
}
} finally {
} catch (e) {
await this.client.unbind();
throw e;
}
await this.client.unbind();
return [groups, users];
}
@@ -453,8 +455,9 @@ export class LdapDirectoryService implements IDirectoryService {
try {
await this.client.bind(user, pass);
} catch {
} catch (error) {
await this.client.unbind();
throw error;
}
}

View File

@@ -1,31 +0,0 @@
import { deletePassword, getPassword, setPassword } from "keytar";
import { StorageService } from "@/jslib/common/src/abstractions/storage.service";
export class KeytarSecureStorageService implements StorageService {
constructor(private serviceName: string) {}
get<T>(key: string): Promise<T> {
return getPassword(this.serviceName, key).then((val) => {
return JSON.parse(val) as T;
});
}
async has(key: string): Promise<boolean> {
return (await this.get(key)) != null;
}
save(key: string, obj: any): Promise<any> {
// keytar throws if you try to save a falsy value: https://github.com/atom/node-keytar/issues/86
// handle this by removing the key instead
if (!obj) {
return this.remove(key);
}
return setPassword(this.serviceName, key, JSON.stringify(obj));
}
remove(key: string): Promise<any> {
return deletePassword(this.serviceName, key);
}
}

View File

@@ -0,0 +1,40 @@
import { StorageService } from "@/jslib/common/src/abstractions/storage.service";
import { passwords } from "dc-native";
export class NativeSecureStorageService implements StorageService {
constructor(private serviceName: string) {}
get<T>(key: string): Promise<T> {
return passwords
.getPassword(this.serviceName, key)
.then((val: string) => JSON.parse(val) as T)
.catch((e: Error): T => {
if (e.message === passwords.PASSWORD_NOT_FOUND) {
return null;
}
throw e;
});
}
async has(key: string): Promise<boolean> {
return (await this.get(key)) != null;
}
save(key: string, obj: any): Promise<any> {
if (!obj) {
return this.remove(key);
}
return passwords.setPassword(this.serviceName, key, JSON.stringify(obj));
}
remove(key: string): Promise<any> {
return passwords.deletePassword(this.serviceName, key).catch((e: Error) => {
if (e.message === passwords.PASSWORD_NOT_FOUND) {
return;
}
throw e;
});
}
}

View File

@@ -1,3 +1,5 @@
import { passwords } from "dc-native";
import { StateVersion } from "@/jslib/common/src/enums/stateVersion";
import { StateMigrationService as BaseStateMigrationService } from "@/jslib/common/src/services/stateMigration.service";
@@ -61,6 +63,13 @@ export class StateMigrationService extends BaseStateMigrationService {
break;
case StateVersion.Two:
await this.migrateStateFrom2To3();
break;
case StateVersion.Three:
await this.migrateStateFrom3To4();
break;
case StateVersion.Four:
await this.migrateStateFrom4To5();
break;
}
currentStateVersion += 1;
}
@@ -168,6 +177,50 @@ export class StateMigrationService extends BaseStateMigrationService {
}
}
}
/**
* Migrates Windows credential store entries previously written by keytar (UTF-8 blob) to
* the UTF-16 format expected by desktop_core. No-ops on non-Windows platforms.
*
* This migration is needed because keytar used CredWriteA (storing blobs as raw UTF-8 bytes)
* while desktop_core uses CredWriteW (storing blobs as UTF-16). Reading old keytar credentials
* through desktop_core produces garbled output without this migration.
*/
protected async migrateStateFrom3To4(useSecureStorageForSecrets = true): Promise<void> {
if (useSecureStorageForSecrets && process.platform === "win32") {
const serviceName = "Bitwarden Directory Connector";
const authenticatedUserIds = await this.get<string[]>(StateKeys.authenticatedAccounts);
if (authenticatedUserIds?.length) {
const credentialKeys = [
SecureStorageKeys.ldap,
SecureStorageKeys.gsuite,
SecureStorageKeys.azure,
SecureStorageKeys.entra,
SecureStorageKeys.okta,
SecureStorageKeys.oneLogin,
];
await Promise.all(
authenticatedUserIds.flatMap((userId) =>
credentialKeys.map((key) =>
passwords.migrateKeytarPassword(serviceName, `${userId}_${key}`),
),
),
);
}
}
const globals = await this.getGlobals();
globals.stateVersion = StateVersion.Four;
await this.set(StateKeys.global, globals);
}
protected async migrateStateFrom4To5(): Promise<void> {
const globals = await this.getGlobals();
globals.stateVersion = StateVersion.Five;
await this.set(StateKeys.global, globals);
}
protected async migrateStateFrom2To3(useSecureStorageForSecrets = true): Promise<void> {
if (useSecureStorageForSecrets) {
const authenticatedUserIds = await this.get<string[]>(StateKeys.authenticatedAccounts);

View File

@@ -6,6 +6,8 @@ import { MessagingService } from "@/jslib/common/src/abstractions/messaging.serv
import { OrganizationImportRequest } from "@/jslib/common/src/models/request/organizationImportRequest";
import { ApiService } from "@/jslib/common/src/services/api.service";
import { GroupEntry } from "@/src/models/groupEntry";
import { getSyncConfiguration } from "../../utils/openldap/config-fixtures";
import { DirectoryFactoryService } from "../abstractions/directory-factory.service";
import { DirectoryType } from "../enums/directoryType";
@@ -134,4 +136,134 @@ describe("SyncService", () => {
expect(apiService.postPublicImportDirectory).not.toHaveBeenCalled();
});
describe("nested and circular group handling", () => {
function createGroup(
name: string,
userExternalIds: string[] = [],
groupMemberReferenceIds: string[] = [],
) {
return GroupEntry.fromJSON({
name,
referenceId: name,
externalId: name,
userMemberExternalIds: userExternalIds,
groupMemberReferenceIds: groupMemberReferenceIds,
users: [],
});
}
function setupSyncWithGroups(groups: GroupEntry[]) {
const mockDirectoryService = mock<LdapDirectoryService>();
mockDirectoryService.getEntries.mockResolvedValue([groups, []]);
directoryFactory.createService.mockReturnValue(mockDirectoryService);
stateService.getSync.mockResolvedValue(getSyncConfiguration({ groups: true, users: true }));
cryptoFunctionService.hash.mockResolvedValue(new ArrayBuffer(1));
stateService.getLastSyncHash.mockResolvedValue("unique hash");
singleRequestBuilder.buildRequest.mockReturnValue([
{ members: [], groups: [], overwriteExisting: true, largeImport: false },
]);
}
it("should handle simple circular reference (A ↔ B) without stack overflow", async () => {
const groupA = createGroup("GroupA", ["userA"], ["GroupB"]);
const groupB = createGroup("GroupB", ["userB"], ["GroupA"]);
setupSyncWithGroups([groupA, groupB]);
const [groups] = await syncService.sync(true, true);
const [a, b] = groups;
expect(a.userMemberExternalIds).toEqual(new Set(["userA", "userB"]));
expect(b.userMemberExternalIds).toEqual(new Set(["userA", "userB"]));
});
it("should handle longer circular chain (A → B → C → A) without stack overflow", async () => {
const groupA = createGroup("GroupA", ["userA"], ["GroupB"]);
const groupB = createGroup("GroupB", ["userB"], ["GroupC"]);
const groupC = createGroup("GroupC", ["userC"], ["GroupA"]);
setupSyncWithGroups([groupA, groupB, groupC]);
const [groups] = await syncService.sync(true, true);
const allUsers = new Set(["userA", "userB", "userC"]);
for (const group of groups) {
expect(group.userMemberExternalIds).toEqual(allUsers);
}
});
it("should handle diamond structure (A → [B, C] → D)", async () => {
const groupA = createGroup("GroupA", ["userA"], ["GroupB", "GroupC"]);
const groupB = createGroup("GroupB", ["userB"], ["GroupD"]);
const groupC = createGroup("GroupC", ["userC"], ["GroupD"]);
const groupD = createGroup("GroupD", ["userD"], []);
setupSyncWithGroups([groupA, groupB, groupC, groupD]);
const [groups] = await syncService.sync(true, true);
const [a, b, c, d] = groups;
expect(a.userMemberExternalIds).toEqual(new Set(["userA", "userB", "userC", "userD"]));
expect(b.userMemberExternalIds).toEqual(new Set(["userB", "userD"]));
expect(c.userMemberExternalIds).toEqual(new Set(["userC", "userD"]));
expect(d.userMemberExternalIds).toEqual(new Set(["userD"]));
});
it("should handle deep nesting with circular reference at leaf", async () => {
// Structure: A → B → C → D → B (cycle back to B)
const groupA = createGroup("GroupA", ["userA"], ["GroupB"]);
const groupB = createGroup("GroupB", ["userB"], ["GroupC"]);
const groupC = createGroup("GroupC", ["userC"], ["GroupD"]);
const groupD = createGroup("GroupD", ["userD"], ["GroupB"]);
setupSyncWithGroups([groupA, groupB, groupC, groupD]);
const [groups] = await syncService.sync(true, true);
const [a, b, c, d] = groups;
const cycleUsers = new Set(["userB", "userC", "userD"]);
expect(a.userMemberExternalIds).toEqual(new Set(["userA", ...cycleUsers]));
expect(b.userMemberExternalIds).toEqual(cycleUsers);
expect(c.userMemberExternalIds).toEqual(cycleUsers);
expect(d.userMemberExternalIds).toEqual(cycleUsers);
});
it("should handle complex structure with multiple cycles and shared members", async () => {
// Structure:
// A → [B, C]
// B → [D, E]
// C → [E, F]
// D → A (cycle)
// E → C (cycle)
// F → (leaf)
const groupA = createGroup("GroupA", ["userA"], ["GroupB", "GroupC"]);
const groupB = createGroup("GroupB", ["userB"], ["GroupD", "GroupE"]);
const groupC = createGroup("GroupC", ["userC"], ["GroupE", "GroupF"]);
const groupD = createGroup("GroupD", ["userD"], ["GroupA"]);
const groupE = createGroup("GroupE", ["userE"], ["GroupC"]);
const groupF = createGroup("GroupF", ["userF"], []);
setupSyncWithGroups([groupA, groupB, groupC, groupD, groupE, groupF]);
const [groups] = await syncService.sync(true, true);
const allUsers = new Set(["userA", "userB", "userC", "userD", "userE", "userF"]);
const a = groups.find((g) => g.name === "GroupA");
const b = groups.find((g) => g.name === "GroupB");
const c = groups.find((g) => g.name === "GroupC");
const d = groups.find((g) => g.name === "GroupD");
const e = groups.find((g) => g.name === "GroupE");
const f = groups.find((g) => g.name === "GroupF");
// A can reach all groups, so it gets all users
expect(a.userMemberExternalIds).toEqual(allUsers);
// B reaches D, E, and through cycles reaches everything
expect(b.userMemberExternalIds).toEqual(allUsers);
// C reaches E (which cycles back to C) and F
expect(c.userMemberExternalIds).toEqual(new Set(["userC", "userE", "userF"]));
// D cycles to A, which reaches everything
expect(d.userMemberExternalIds).toEqual(allUsers);
// E cycles to C, picking up C's descendants
expect(e.userMemberExternalIds).toEqual(new Set(["userC", "userE", "userF"]));
// F is a leaf
expect(f.userMemberExternalIds).toEqual(new Set(["userF"]));
});
});
});

View File

@@ -196,14 +196,27 @@ export class SyncService {
return users == null ? null : users.filter((u) => u.email?.length <= 256);
}
private flattenUsersToGroups(levelGroups: GroupEntry[], allGroups: GroupEntry[]): Set<string> {
private flattenUsersToGroups(
levelGroups: GroupEntry[],
allGroups: GroupEntry[],
visitedGroups?: Set<string>,
): Set<string> {
let allUsers = new Set<string>();
if (allGroups == null) {
return allUsers;
}
for (const group of levelGroups) {
const visited = visitedGroups ?? new Set<string>();
if (visited.has(group.referenceId)) {
continue;
}
visited.add(group.referenceId);
const childGroups = allGroups.filter((g) => group.groupMemberReferenceIds.has(g.referenceId));
const childUsers = this.flattenUsersToGroups(childGroups, allGroups);
const childUsers = this.flattenUsersToGroups(childGroups, allGroups, visited);
childUsers.forEach((id) => group.userMemberExternalIds.add(id));
allUsers = new Set([...allUsers, ...group.userMemberExternalIds]);
}

View File

@@ -16,7 +16,8 @@
"baseUrl": ".",
"paths": {
"tldjs": ["@/jslib/src/misc/tldjs.noop"],
"@/*": ["./*"]
"@/*": ["./*"],
"dc-native": ["./native/index.d.ts"]
}
},
"include": ["src", "jslib", "scripts", "./*.ts"]

View File

@@ -20,7 +20,8 @@
"resolveJsonModule": true,
"paths": {
"tldjs": ["./jslib/common/src/misc/tldjs.noop"],
"@/*": ["./*"]
"@/*": ["./*"],
"dc-native": ["./native/index.d.ts"]
},
"useDefineForClassFields": false
},

View File

@@ -0,0 +1,308 @@
version: 1
dn: dc=bitwarden,dc=com
dc: bitwarden
objectClass: dcObject
objectClass: organization
o: Bitwarden
# Organizational Units
dn: ou=Human Resources,dc=bitwarden,dc=com
changetype: add
ou: Human Resources
objectClass: top
objectClass: organizationalUnit
dn: ou=Engineering,dc=bitwarden,dc=com
changetype: add
ou: Engineering
objectClass: top
objectClass: organizationalUnit
dn: ou=Marketing,dc=bitwarden,dc=com
changetype: add
ou: Marketing
objectClass: top
objectClass: organizationalUnit
# Users - Human Resources
dn: cn=Roland Dyke,ou=Human Resources,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Roland Dyke
sn: Dyke
description: This is Roland Dyke's description
facsimileTelephoneNumber: +1 804 674-5794
l: San Francisco
ou: Human Resources
postalAddress: Human Resources$San Francisco
telephoneNumber: +1 804 831-5121
title: Supreme Human Resources Writer
userPassword: Password1
uid: DykeR
givenName: Roland
mail: DykeR@220af87272f04218bb8dd81d50fb19f5.bitwarden.com
carLicense: 4CMGOJ
departmentNumber: 2838
employeeType: Contract
homePhone: +1 804 936-4965
initials: R. D.
mobile: +1 804 592-3734
pager: +1 804 285-2962
roomNumber: 9890
dn: cn=Teirtza Kara,ou=Human Resources,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Teirtza Kara
sn: Kara
description: This is Teirtza Kara's description
facsimileTelephoneNumber: +1 206 759-2040
l: San Francisco
ou: Human Resources
postalAddress: Human Resources$San Francisco
telephoneNumber: +1 206 562-1407
title: Junior Human Resources President
userPassword: Password1
uid: KaraT
givenName: Teirtza
mail: KaraT@c2afe8b3509f4a20b2b784841685bd74.bitwarden.com
carLicense: O9GAN2
departmentNumber: 3880
employeeType: Employee
homePhone: +1 206 154-4842
initials: T. K.
mobile: +1 206 860-1835
pager: +1 206 684-1438
roomNumber: 9079
# Users - Engineering
dn: cn=Alice Chen,ou=Engineering,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Alice Chen
sn: Chen
description: Senior DevOps Engineer
l: Seattle
ou: Engineering
telephoneNumber: +1 206 555-0101
title: Senior DevOps Engineer
userPassword: Password1
uid: ChenA
givenName: Alice
mail: ChenA@bitwarden.com
employeeType: Employee
dn: cn=Bob Martinez,ou=Engineering,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Bob Martinez
sn: Martinez
description: Platform Engineer
l: Austin
ou: Engineering
telephoneNumber: +1 512 555-0102
title: Platform Engineer
userPassword: Password1
uid: MartinezB
givenName: Bob
mail: MartinezB@bitwarden.com
employeeType: Employee
dn: cn=Carol Williams,ou=Engineering,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Carol Williams
sn: Williams
description: QA Lead
l: Denver
ou: Engineering
telephoneNumber: +1 303 555-0103
title: QA Lead
userPassword: Password1
uid: WilliamsC
givenName: Carol
mail: WilliamsC@bitwarden.com
employeeType: Employee
dn: cn=David Kim,ou=Engineering,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: David Kim
sn: Kim
description: QA Engineer
l: Portland
ou: Engineering
telephoneNumber: +1 503 555-0104
title: QA Engineer
userPassword: Password1
uid: KimD
givenName: David
mail: KimD@bitwarden.com
employeeType: Contractor
# Users - Marketing
dn: cn=Eva Johnson,ou=Marketing,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Eva Johnson
sn: Johnson
description: Marketing Director
l: New York
ou: Marketing
telephoneNumber: +1 212 555-0105
title: Marketing Director
userPassword: Password1
uid: JohnsonE
givenName: Eva
mail: JohnsonE@bitwarden.com
employeeType: Employee
dn: cn=Frank Lee,ou=Marketing,dc=bitwarden,dc=com
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
cn: Frank Lee
sn: Lee
description: Content Strategist
l: Chicago
ou: Marketing
telephoneNumber: +1 312 555-0106
title: Content Strategist
userPassword: Password1
uid: LeeF
givenName: Frank
mail: LeeF@bitwarden.com
employeeType: Employee
# ============================================================
# GROUP HIERARCHY
# ============================================================
# Structure (arrows show "contains" relationship):
#
# AllStaff
# ├── Engineering ◄────────────────┐ (CYCLE from Platform)
# │ ├── DevOps │
# │ │ └── Platform ────────┘
# │ └── QA
# ├── Marketing
# └── HR
#
# Contractors ─── DevOps (diamond: second path to Platform)
#
# TestNestA ◄──► TestNestB (simple bidirectional cycle)
#
# ============================================================
# Leaf group - Platform team (CYCLES BACK to Engineering)
dn: cn=Platform,dc=bitwarden,dc=com
changetype: add
cn: Platform
member: cn=Bob Martinez,ou=Engineering,dc=bitwarden,dc=com
member: cn=Engineering,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# DevOps group - contains Platform subgroup
dn: cn=DevOps,dc=bitwarden,dc=com
changetype: add
cn: DevOps
member: cn=Alice Chen,ou=Engineering,dc=bitwarden,dc=com
member: cn=Platform,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# QA group
dn: cn=QA,dc=bitwarden,dc=com
changetype: add
cn: QA
member: cn=Carol Williams,ou=Engineering,dc=bitwarden,dc=com
member: cn=David Kim,ou=Engineering,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# Engineering group - contains DevOps and QA subgroups
dn: cn=Engineering,dc=bitwarden,dc=com
changetype: add
cn: Engineering
member: cn=DevOps,dc=bitwarden,dc=com
member: cn=QA,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# Marketing group
dn: cn=Marketing,dc=bitwarden,dc=com
changetype: add
cn: Marketing
member: cn=Eva Johnson,ou=Marketing,dc=bitwarden,dc=com
member: cn=Frank Lee,ou=Marketing,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# HR group
dn: cn=HR,dc=bitwarden,dc=com
changetype: add
cn: HR
member: cn=Roland Dyke,ou=Human Resources,dc=bitwarden,dc=com
member: cn=Teirtza Kara,ou=Human Resources,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# AllStaff - top-level group containing all departments
dn: cn=AllStaff,dc=bitwarden,dc=com
changetype: add
cn: AllStaff
member: cn=Engineering,dc=bitwarden,dc=com
member: cn=Marketing,dc=bitwarden,dc=com
member: cn=HR,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# Contractors group - creates diamond pattern (second path to Platform via DevOps)
dn: cn=Contractors,dc=bitwarden,dc=com
changetype: add
cn: Contractors
member: cn=DevOps,dc=bitwarden,dc=com
member: cn=David Kim,ou=Engineering,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
# Simple bidirectional cycle test groups (preserved from original)
dn: cn=TestNestA,dc=bitwarden,dc=com
changetype: add
cn: TestNestA
member: cn=TestNestB,dc=bitwarden,dc=com
member: cn=Roland Dyke,ou=Human Resources,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top
dn: cn=TestNestB,dc=bitwarden,dc=com
changetype: add
cn: TestNestB
member: cn=TestNestA,dc=bitwarden,dc=com
member: cn=Teirtza Kara,ou=Human Resources,dc=bitwarden,dc=com
objectclass: groupOfNames
objectclass: top

View File

@@ -1,6 +1,5 @@
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
const webpack = require("webpack");
@@ -24,7 +23,6 @@ const moduleRules = [
];
const plugins = [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [{ from: "./src/locales", to: "locales" }],
}),
@@ -64,6 +62,7 @@ const config = {
output: {
filename: "[name].js",
path: path.resolve(__dirname, "build-cli"),
clean: true,
},
module: { rules: moduleRules },
plugins: plugins,

View File

@@ -1,7 +1,6 @@
const path = require("path");
const { merge } = require("webpack-merge");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");
@@ -23,6 +22,7 @@ const common = {
output: {
filename: "[name].js",
path: path.resolve(__dirname, "build"),
clean: true,
},
};
@@ -48,7 +48,6 @@ const main = {
],
},
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({
patterns: [
"./package.json",
@@ -59,7 +58,6 @@ const main = {
],
externals: {
"electron-reload": "commonjs2 electron-reload",
keytar: "commonjs2 keytar",
},
};

View File

@@ -55,6 +55,9 @@ const renderer = {
node: {
__dirname: false,
},
externals: {
"dc-native": "commonjs2 dc-native",
},
entry: {
"app/main": "./src/app/main.ts",
},