1
0
mirror of https://github.com/bitwarden/browser synced 2026-01-31 00:33:33 +00:00

Revert "[deps] Platform: Update napi to v3 (major) (#16053)"

This reverts commit 852248d5fa.
This commit is contained in:
Todd Martin
2026-01-02 15:42:03 -05:00
parent 7ef5204791
commit 852d12e9ab
13 changed files with 392 additions and 1832 deletions

View File

@@ -209,7 +209,7 @@ jobs:
- name: Set up environment
run: |
sudo apt-get update
sudo apt-get -y install pkg-config libxss-dev rpm flatpak flatpak-builder
sudo apt-get -y install pkg-config libxss-dev rpm musl-dev musl-tools flatpak flatpak-builder
- name: Set up Snap
run: sudo snap install snapcraft --classic
@@ -262,10 +262,12 @@ jobs:
env:
PKG_CONFIG_ALLOW_CROSS: true
PKG_CONFIG_ALL_STATIC: true
TARGET: musl
# Note: It is important that we use the release build because some compute heavy
# operations such as key derivation for oo7 on linux are too slow in debug mode
# operations such as key derivation for oo7 on linux are too slow in debug mode
run: |
node build.js --target=x86_64-unknown-linux-gnu --release
rustup target add x86_64-unknown-linux-musl
node build.js --target=x86_64-unknown-linux-musl --release
- name: Build application
run: npm run dist:lin
@@ -365,7 +367,7 @@ jobs:
- name: Set up environment
run: |
sudo apt-get update
sudo apt-get -y install pkg-config libxss-dev rpm flatpak flatpak-builder squashfs-tools ruby ruby-dev rubygems build-essential
sudo apt-get -y install pkg-config libxss-dev rpm musl-dev musl-tools flatpak flatpak-builder squashfs-tools ruby ruby-dev rubygems build-essential
sudo gem install --no-document fpm
- name: Set up Snap
@@ -425,10 +427,12 @@ jobs:
env:
PKG_CONFIG_ALLOW_CROSS: true
PKG_CONFIG_ALL_STATIC: true
TARGET: musl
# Note: It is important that we use the release build because some compute heavy
# operations such as key derivation for oo7 on linux are too slow in debug mode
run: |
node build.js --target=aarch64-unknown-linux-gnu --release
rustup target add aarch64-unknown-linux-musl
node build.js --target=aarch64-unknown-linux-musl --release
- name: Check index.d.ts generated
if: github.event_name == 'pull_request' && steps.cache.outputs.cache-hit != 'true'

View File

@@ -685,9 +685,9 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "convert_case"
version = "0.8.0"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baaaa0ecca5b51987b9423ccdc971514dd8b0bb7b4060b983d3664dad3f1f89f"
checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
dependencies = [
"unicode-segmentation",
]
@@ -746,6 +746,16 @@ dependencies = [
"typenum",
]
[[package]]
name = "ctor"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"
dependencies = [
"quote",
"syn",
]
[[package]]
name = "ctor"
version = "0.5.0"
@@ -1850,33 +1860,32 @@ dependencies = [
[[package]]
name = "napi"
version = "3.3.0"
version = "2.16.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1b74e3dce5230795bb4d2821b941706dee733c7308752507254b0497f39cad7"
checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"
dependencies = [
"bitflags",
"ctor",
"napi-build",
"ctor 0.2.9",
"napi-derive",
"napi-sys",
"nohash-hasher",
"rustc-hash",
"once_cell",
"tokio",
]
[[package]]
name = "napi-build"
version = "2.2.3"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcae8ad5609d14afb3a3b91dee88c757016261b151e9dcecabf1b2a31a6cab14"
checksum = "03acbfa4f156a32188bfa09b86dc11a431b5725253fc1fc6f6df5bed273382c4"
[[package]]
name = "napi-derive"
version = "3.2.5"
version = "2.16.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7552d5a579b834614bbd496db5109f1b9f1c758f08224b0dee1e408333adf0d0"
checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"
dependencies = [
"cfg-if",
"convert_case",
"ctor",
"napi-derive-backend",
"proc-macro2",
"quote",
@@ -1885,22 +1894,24 @@ dependencies = [
[[package]]
name = "napi-derive-backend"
version = "2.2.0"
version = "1.0.75"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f6a81ac7486b70f2532a289603340862c06eea5a1e650c1ffeda2ce1238516a"
checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"
dependencies = [
"convert_case",
"once_cell",
"proc-macro2",
"quote",
"regex",
"semver",
"syn",
]
[[package]]
name = "napi-sys"
version = "3.0.0"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e4e7135a8f97aa0f1509cce21a8a1f9dcec1b50d8dee006b48a5adb69a9d64d"
checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"
dependencies = [
"libloading",
]
@@ -1918,12 +1929,6 @@ dependencies = [
"memoffset",
]
[[package]]
name = "nohash-hasher"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "7.1.3"
@@ -2493,7 +2498,7 @@ dependencies = [
name = "process_isolation"
version = "0.0.0"
dependencies = [
"ctor",
"ctor 0.5.0",
"desktop_core",
"libc",
"tracing",
@@ -2608,6 +2613,18 @@ dependencies = [
"thiserror 2.0.17",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
@@ -2680,12 +2697,6 @@ dependencies = [
"winapi",
]
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_version"
version = "0.4.1"

View File

@@ -42,9 +42,9 @@ interprocess = "=2.2.1"
libc = "=0.2.178"
linux-keyutils = "=0.2.4"
memsec = "=0.7.0"
napi = "=3.3.0"
napi-build = "=2.2.3"
napi-derive = "=3.2.5"
napi = "=2.16.17"
napi-build = "=2.2.0"
napi-derive = "=2.16.13"
oo7 = "=0.5.0"
pin-project = "=1.1.10"
pkcs8 = "=0.10.2"

View File

@@ -11,8 +11,8 @@ const rustTargetsMap = {
"aarch64-pc-windows-msvc": { nodeArch: 'arm64', platform: 'win32' },
"x86_64-apple-darwin": { nodeArch: 'x64', platform: 'darwin' },
"aarch64-apple-darwin": { nodeArch: 'arm64', platform: 'darwin' },
'x86_64-unknown-linux-gnu': { nodeArch: 'x64', platform: 'linux' },
'aarch64-unknown-linux-gnu': { nodeArch: 'arm64', platform: 'linux' },
'x86_64-unknown-linux-musl': { nodeArch: 'x64', platform: 'linux' },
'aarch64-unknown-linux-musl': { nodeArch: 'arm64', platform: 'linux' },
}
// Ensure the dist directory exists

View File

@@ -7,9 +7,9 @@ pub struct NativeImporterMetadata {
/// Identifies the importer
pub id: String,
/// Describes the strategies used to obtain imported data
pub loaders: Vec<String>,
pub loaders: Vec<&'static str>,
/// Identifies the instructions for the importer
pub instructions: String,
pub instructions: &'static str,
}
/// Returns a map of supported importers based on the current platform.
@@ -36,9 +36,9 @@ pub fn get_supported_importers<T: InstalledBrowserRetriever>(
PLATFORM_SUPPORTED_BROWSERS.iter().map(|b| b.name).collect();
for (id, browser_name) in IMPORTERS {
let mut loaders: Vec<String> = vec!["file".to_string()];
let mut loaders: Vec<&'static str> = vec!["file"];
if supported.contains(browser_name) {
loaders.push("chromium".to_string());
loaders.push("chromium");
}
if installed_browsers.contains(&browser_name.to_string()) {
@@ -47,7 +47,7 @@ pub fn get_supported_importers<T: InstalledBrowserRetriever>(
NativeImporterMetadata {
id: id.to_string(),
loaders,
instructions: "chromium".to_string(),
instructions: "chromium",
},
);
}
@@ -79,9 +79,12 @@ mod tests {
map.keys().cloned().collect()
}
fn get_loaders(map: &HashMap<String, NativeImporterMetadata>, id: &str) -> HashSet<String> {
fn get_loaders(
map: &HashMap<String, NativeImporterMetadata>,
id: &str,
) -> HashSet<&'static str> {
map.get(id)
.map(|m| m.loaders.iter().cloned().collect::<HashSet<_>>())
.map(|m| m.loaders.iter().copied().collect::<HashSet<_>>())
.unwrap_or_default()
}
@@ -104,7 +107,7 @@ mod tests {
for (key, meta) in map.iter() {
assert_eq!(&meta.id, key);
assert_eq!(meta.instructions, "chromium");
assert!(meta.loaders.contains(&"file".to_owned()));
assert!(meta.loaders.contains(&"file"));
}
}
@@ -144,7 +147,7 @@ mod tests {
for (key, meta) in map.iter() {
assert_eq!(&meta.id, key);
assert_eq!(meta.instructions, "chromium");
assert!(meta.loaders.contains(&"file".to_owned()));
assert!(meta.loaders.contains(&"file"));
}
}
@@ -180,7 +183,7 @@ mod tests {
for (key, meta) in map.iter() {
assert_eq!(&meta.id, key);
assert_eq!(meta.instructions, "chromium");
assert!(meta.loaders.contains(&"file".to_owned()));
assert!(meta.loaders.contains(&"file"));
}
}

View File

@@ -1,7 +1,125 @@
/* auto-generated by NAPI-RS */
/* tslint:disable */
/* eslint-disable */
export declare namespace autofill {
export class AutofillIpcServer {
/* auto-generated by NAPI-RS */
export declare namespace passwords {
/** The error message returned when a password is not found during retrieval or deletion. */
export const PASSWORD_NOT_FOUND: string
/**
* Fetch the stored password from the keychain.
* Throws {@link Error} with message {@link PASSWORD_NOT_FOUND} if the password does not exist.
*/
export function getPassword(service: string, account: string): Promise<string>
/**
* Save the password to the keychain. Adds an entry if none exists otherwise updates the
* existing entry.
*/
export function setPassword(service: string, account: string, password: string): Promise<void>
/**
* Delete the stored password from the keychain.
* Throws {@link Error} with message {@link PASSWORD_NOT_FOUND} if the password does not exist.
*/
export function deletePassword(service: string, account: string): Promise<void>
/** Checks if the os secure storage is available */
export function isAvailable(): Promise<boolean>
}
export declare namespace biometrics {
export function prompt(hwnd: Buffer, message: string): Promise<boolean>
export function available(): Promise<boolean>
export function setBiometricSecret(service: string, account: string, secret: string, keyMaterial: KeyMaterial | undefined | null, ivB64: string): Promise<string>
/**
* Retrieves the biometric secret for the given service and account.
* Throws Error with message [`passwords::PASSWORD_NOT_FOUND`] if the secret does not exist.
*/
export function getBiometricSecret(service: string, account: string, keyMaterial?: KeyMaterial | undefined | null): Promise<string>
/**
* Derives key material from biometric data. Returns a string encoded with a
* base64 encoded key and the base64 encoded challenge used to create it
* separated by a `|` character.
*
* If the iv is provided, it will be used as the challenge. Otherwise a random challenge will
* be generated.
*
* `format!("<key_base64>|<iv_base64>")`
*/
export function deriveKeyMaterial(iv?: string | undefined | null): Promise<OsDerivedKey>
export interface KeyMaterial {
osKeyPartB64: string
clientKeyPartB64?: string
}
export interface OsDerivedKey {
keyB64: string
ivB64: string
}
}
export declare namespace biometrics_v2 {
export function initBiometricSystem(): BiometricLockSystem
export function authenticate(biometricLockSystem: BiometricLockSystem, hwnd: Buffer, message: string): Promise<boolean>
export function authenticateAvailable(biometricLockSystem: BiometricLockSystem): Promise<boolean>
export function enrollPersistent(biometricLockSystem: BiometricLockSystem, userId: string, key: Buffer): Promise<void>
export function provideKey(biometricLockSystem: BiometricLockSystem, userId: string, key: Buffer): Promise<void>
export function unlock(biometricLockSystem: BiometricLockSystem, userId: string, hwnd: Buffer): Promise<Buffer>
export function unlockAvailable(biometricLockSystem: BiometricLockSystem, userId: string): Promise<boolean>
export function hasPersistent(biometricLockSystem: BiometricLockSystem, userId: string): Promise<boolean>
export function unenroll(biometricLockSystem: BiometricLockSystem, userId: string): Promise<void>
export class BiometricLockSystem { }
}
export declare namespace clipboards {
export function read(): Promise<string>
export function write(text: string, password: boolean): Promise<void>
}
export declare namespace sshagent {
export interface PrivateKey {
privateKey: string
name: string
cipherId: string
}
export interface SshKey {
privateKey: string
publicKey: string
keyFingerprint: string
}
export interface SshUiRequest {
cipherId?: string
isList: boolean
processName: string
isForwarding: boolean
namespace?: string
}
export function serve(callback: (err: Error | null, arg: SshUiRequest) => any): Promise<SshAgentState>
export function stop(agentState: SshAgentState): void
export function isRunning(agentState: SshAgentState): boolean
export function setKeys(agentState: SshAgentState, newKeys: Array<PrivateKey>): void
export function lock(agentState: SshAgentState): void
export function clearKeys(agentState: SshAgentState): void
export class SshAgentState { }
}
export declare namespace processisolations {
export function disableCoredumps(): Promise<void>
export function isCoreDumpingDisabled(): Promise<boolean>
export function isolateProcess(): Promise<void>
}
export declare namespace powermonitors {
export function onLock(callback: (err: Error | null, ) => any): Promise<void>
export function isLockMonitorAvailable(): Promise<boolean>
}
export declare namespace windows_registry {
export function createKey(key: string, subkey: string, value: string): Promise<void>
export function deleteKey(key: string, subkey: string): Promise<void>
}
export declare namespace ipc {
export interface IpcMessage {
clientId: number
kind: IpcMessageType
message?: string
}
export const enum IpcMessageType {
Connected = 0,
Disconnected = 1,
Message = 2
}
export class IpcServer {
/**
* Create and start the IPC server without blocking.
*
@@ -9,43 +127,34 @@ export declare namespace autofill {
* 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, nativeStatusCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: NativeStatus) => void): Promise<AutofillIpcServer>
static listen(name: string, callback: (error: null | Error, message: IpcMessage) => void): Promise<IpcServer>
/** Return the path to the IPC server. */
getPath(): string
/** Stop the IPC server. */
stop(): void
completeRegistration(clientId: number, sequenceNumber: number, response: PasskeyRegistrationResponse): number
completeAssertion(clientId: number, sequenceNumber: number, response: PasskeyAssertionResponse): number
completeError(clientId: number, sequenceNumber: number, error: string): number
/**
* Send a message over the IPC server to all the connected clients
*
* @return The number of clients that the message was sent to. Note that the number of
* messages actually received may be less, as some clients could disconnect before
* receiving the message.
*/
send(message: string): number
}
export interface NativeStatus {
key: string
value: string
}
export declare namespace autostart {
export function setAutostart(autostart: boolean, params: Array<string>): Promise<void>
}
export declare namespace autofill {
export function runCommand(value: string): Promise<string>
export const enum UserVerification {
Preferred = 'preferred',
Required = 'required',
Discouraged = 'discouraged'
}
export interface PasskeyAssertionRequest {
rpId: string
clientDataHash: Array<number>
userVerification: UserVerification
allowedCredentials: Array<Array<number>>
windowXy: Position
}
export interface PasskeyAssertionResponse {
rpId: string
userHandle: Array<number>
signature: Array<number>
clientDataHash: Array<number>
authenticatorData: Array<number>
credentialId: Array<number>
}
export interface PasskeyAssertionWithoutUserInterfaceRequest {
rpId: string
credentialId: Array<number>
userName: string
userHandle: Array<number>
recordIdentifier?: string
clientDataHash: Array<number>
userVerification: UserVerification
windowXy: Position
export interface Position {
x: number
y: number
}
export interface PasskeyRegistrationRequest {
rpId: string
@@ -63,77 +172,71 @@ export declare namespace autofill {
credentialId: Array<number>
attestationObject: Array<number>
}
export interface Position {
x: number
y: number
export interface PasskeyAssertionRequest {
rpId: string
clientDataHash: Array<number>
userVerification: UserVerification
allowedCredentials: Array<Array<number>>
windowXy: Position
}
export function runCommand(value: string): Promise<string>
export const enum UserVerification {
Preferred = 'preferred',
Required = 'required',
Discouraged = 'discouraged'
export interface PasskeyAssertionWithoutUserInterfaceRequest {
rpId: string
credentialId: Array<number>
userName: string
userHandle: Array<number>
recordIdentifier?: string
clientDataHash: Array<number>
userVerification: UserVerification
windowXy: Position
}
export interface NativeStatus {
key: string
value: string
}
export interface PasskeyAssertionResponse {
rpId: string
userHandle: Array<number>
signature: Array<number>
clientDataHash: Array<number>
authenticatorData: Array<number>
credentialId: Array<number>
}
export class IpcServer {
/**
* Create and start the IPC server without blocking.
*
* @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, nativeStatusCallback: (error: null | Error, clientId: number, sequenceNumber: number, message: NativeStatus) => void): Promise<IpcServer>
/** Return the path to the IPC server. */
getPath(): string
/** Stop the IPC server. */
stop(): void
completeRegistration(clientId: number, sequenceNumber: number, response: PasskeyRegistrationResponse): number
completeAssertion(clientId: number, sequenceNumber: number, response: PasskeyAssertionResponse): number
completeError(clientId: number, sequenceNumber: number, error: string): number
}
}
export declare namespace autostart {
export function setAutostart(autostart: boolean, params: Array<string>): Promise<void>
export declare namespace passkey_authenticator {
export function register(): void
}
export declare namespace autotype {
export function getForegroundWindowTitle(): string
export function typeInput(input: Array<number>, keyboardShortcut: Array<string>): void
}
export declare namespace biometrics {
export function available(): Promise<boolean>
/**
* Derives key material from biometric data. Returns a string encoded with a
* base64 encoded key and the base64 encoded challenge used to create it
* separated by a `|` character.
*
* If the iv is provided, it will be used as the challenge. Otherwise a random challenge will
* be generated.
*
* `format!("<key_base64>|<iv_base64>")`
*/
export function deriveKeyMaterial(iv?: string | undefined | null): Promise<OsDerivedKey>
/**
* Retrieves the biometric secret for the given service and account.
* Throws Error with message [`passwords::PASSWORD_NOT_FOUND`] if the secret does not exist.
*/
export function getBiometricSecret(service: string, account: string, keyMaterial?: KeyMaterial | undefined | null): Promise<string>
export interface KeyMaterial {
osKeyPartB64: string
clientKeyPartB64?: string
export declare namespace logging {
export const enum LogLevel {
Trace = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4
}
export interface OsDerivedKey {
keyB64: string
ivB64: string
}
export function prompt(hwnd: Buffer, message: string): Promise<boolean>
export function setBiometricSecret(service: string, account: string, secret: string, keyMaterial: KeyMaterial | undefined | null, ivB64: string): Promise<string>
export function initNapiLog(jsLogFn: (err: Error | null, arg0: LogLevel, arg1: string) => any): void
}
export declare namespace biometrics_v2 {
export class BiometricLockSystem {
}
export function authenticate(biometricLockSystem: BiometricLockSystem, hwnd: Buffer, message: string): Promise<boolean>
export function authenticateAvailable(biometricLockSystem: BiometricLockSystem): Promise<boolean>
export function enrollPersistent(biometricLockSystem: BiometricLockSystem, userId: string, key: Buffer): Promise<void>
export function hasPersistent(biometricLockSystem: BiometricLockSystem, userId: string): Promise<boolean>
export function initBiometricSystem(): BiometricLockSystem
export function provideKey(biometricLockSystem: BiometricLockSystem, userId: string, key: Buffer): Promise<void>
export function unenroll(biometricLockSystem: BiometricLockSystem, userId: string): Promise<void>
export function unlock(biometricLockSystem: BiometricLockSystem, userId: string, hwnd: Buffer): Promise<Buffer>
export function unlockAvailable(biometricLockSystem: BiometricLockSystem, userId: string): Promise<boolean>
}
export declare namespace chromium_importer {
export function getAvailableProfiles(browser: string): Array<ProfileInfo>
/** Returns OS aware metadata describing supported Chromium based importers as a JSON string. */
export function getMetadata(): Record<string, NativeImporterMetadata>
export function importLogins(browser: string, profileId: string): Promise<Array<LoginImportResult>>
export interface ProfileInfo {
id: string
name: string
}
export interface Login {
url: string
username: string
@@ -154,130 +257,12 @@ export declare namespace chromium_importer {
loaders: Array<string>
instructions: string
}
export interface ProfileInfo {
id: string
name: string
}
/** Returns OS aware metadata describing supported Chromium based importers as a JSON string. */
export function getMetadata(): Record<string, NativeImporterMetadata>
export function getAvailableProfiles(browser: string): Array<ProfileInfo>
export function importLogins(browser: string, profileId: string): Promise<Array<LoginImportResult>>
}
export declare namespace clipboards {
export function read(): Promise<string>
export function write(text: string, password: boolean): Promise<void>
}
export declare namespace ipc {
export class NativeIpcServer {
/**
* Create and start the IPC server without blocking.
*
* @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, callback: (error: null | Error, message: IpcMessage) => void): Promise<NativeIpcServer>
/** Return the path to the IPC server. */
getPath(): string
/** Stop the IPC server. */
stop(): void
/**
* Send a message over the IPC server to all the connected clients
*
* @return The number of clients that the message was sent to. Note that the number of
* messages actually received may be less, as some clients could disconnect before
* receiving the message.
*/
send(message: string): number
}
export interface IpcMessage {
clientId: number
kind: IpcMessageType
message?: string
}
export const enum IpcMessageType {
Connected = 0,
Disconnected = 1,
Message = 2
}
}
export declare namespace logging {
export function initNapiLog(jsLogFn: ((err: Error | null, arg0: LogLevel, arg1: string) => any)): void
export const enum LogLevel {
Trace = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4
}
}
export declare namespace passkey_authenticator {
export function register(): void
}
export declare namespace passwords {
/**
* Delete the stored password from the keychain.
* Throws {@link Error} with message {@link 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 {@link Error} with message {@link PASSWORD_NOT_FOUND} if the password does not exist.
*/
export function getPassword(service: string, account: string): Promise<string>
/** Checks if the os secure storage is available */
export function isAvailable(): 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 the
* existing entry.
*/
export function setPassword(service: string, account: string, password: string): Promise<void>
}
export declare namespace powermonitors {
export function isLockMonitorAvailable(): Promise<boolean>
export function onLock(callback: ((err: Error | null, ) => any)): Promise<void>
}
export declare namespace processisolations {
export function disableCoredumps(): Promise<void>
export function isCoreDumpingDisabled(): Promise<boolean>
export function isolateProcess(): Promise<void>
}
export declare namespace sshagent {
export class SshAgentState {
}
export function clearKeys(agentState: SshAgentState): void
export function isRunning(agentState: SshAgentState): boolean
export function lock(agentState: SshAgentState): void
export interface PrivateKey {
privateKey: string
name: string
cipherId: string
}
export function serve(callback: ((err: Error | null, arg: SshUiRequest) => Promise<boolean>)): Promise<SshAgentState>
export function setKeys(agentState: SshAgentState, newKeys: Array<PrivateKey>): void
export interface SshKey {
privateKey: string
publicKey: string
keyFingerprint: string
}
export interface SshUiRequest {
cipherId?: string
isList: boolean
processName: string
isForwarding: boolean
namespace?: string
}
export function stop(agentState: SshAgentState): void
}
export declare namespace windows_registry {
export function createKey(key: string, subkey: string, value: string): Promise<void>
export function deleteKey(key: string, subkey: string): Promise<void>
export declare namespace autotype {
export function getForegroundWindowTitle(): string
export function typeInput(input: Array<number>, keyboardShortcut: Array<string>): void
}

View File

@@ -82,20 +82,20 @@ switch (platform) {
switch (arch) {
case "x64":
nativeBinding = loadFirstAvailable(
["desktop_napi.linux-x64-gnu.node"],
"@bitwarden/desktop-napi-linux-x64-gnu",
["desktop_napi.linux-x64-musl.node", "desktop_napi.linux-x64-gnu.node"],
"@bitwarden/desktop-napi-linux-x64-musl",
);
break;
case "arm64":
nativeBinding = loadFirstAvailable(
["desktop_napi.linux-arm64-gnu.node"],
"@bitwarden/desktop-napi-linux-arm64-gnu",
["desktop_napi.linux-arm64-musl.node", "desktop_napi.linux-arm64-gnu.node"],
"@bitwarden/desktop-napi-linux-arm64-musl",
);
break;
case "arm":
nativeBinding = loadFirstAvailable(
["desktop_napi.linux-arm-gnu.node"],
"@bitwarden/desktop-napi-linux-arm-gnu",
["desktop_napi.linux-arm-musl.node", "desktop_napi.linux-arm-gnu.node"],
"@bitwarden/desktop-napi-linux-arm-musl",
);
localFileExisted = existsSync(join(__dirname, "desktop_napi.linux-arm-gnueabihf.node"));
try {

View File

@@ -3,23 +3,27 @@
"version": "0.1.0",
"description": "",
"scripts": {
"build": "node scripts/build.js",
"build": "napi build --platform --js false",
"test": "cargo test"
},
"author": "",
"license": "GPL-3.0",
"devDependencies": {
"@napi-rs/cli": "3.2.0"
"@napi-rs/cli": "2.18.4"
},
"napi": {
"binaryName": "desktop_napi",
"targets": [
"aarch64-apple-darwin",
"aarch64-pc-windows-msvc",
"aarch64-unknown-linux-gnu",
"armv7-unknown-linux-gnueabihf",
"i686-pc-windows-msvc",
"x86_64-unknown-linux-gnu"
]
"name": "desktop_napi",
"triples": {
"defaults": true,
"additional": [
"x86_64-unknown-linux-musl",
"aarch64-unknown-linux-gnu",
"i686-pc-windows-msvc",
"armv7-unknown-linux-gnueabihf",
"aarch64-apple-darwin",
"aarch64-unknown-linux-musl",
"aarch64-pc-windows-msvc"
]
}
}
}

View File

@@ -290,7 +290,7 @@ pub mod sshagent {
use napi::{
bindgen_prelude::Promise,
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
threadsafe_function::{ErrorStrategy::CalleeHandled, ThreadsafeFunction},
};
use tokio::{self, sync::Mutex};
use tracing::error;
@@ -326,15 +326,13 @@ pub mod sshagent {
#[allow(clippy::unused_async)] // FIXME: Remove unused async!
#[napi]
pub async fn serve(
callback: ThreadsafeFunction<SshUIRequest, Promise<bool>>,
callback: ThreadsafeFunction<SshUIRequest, CalleeHandled>,
) -> napi::Result<SshAgentState> {
let (auth_request_tx, mut auth_request_rx) =
tokio::sync::mpsc::channel::<desktop_core::ssh_agent::SshAgentUIRequest>(32);
let (auth_response_tx, auth_response_rx) =
tokio::sync::broadcast::channel::<(u32, bool)>(32);
let auth_response_tx_arc = Arc::new(Mutex::new(auth_response_tx));
// Wrap callback in Arc so it can be shared across spawned tasks
let callback = Arc::new(callback);
tokio::spawn(async move {
let _ = auth_response_rx;
@@ -344,50 +342,42 @@ pub mod sshagent {
tokio::spawn(async move {
let auth_response_tx_arc = cloned_response_tx_arc;
let callback = cloned_callback;
// In NAPI v3, obtain the JS callback return as a Promise<boolean> and await it
// in Rust
let (tx, rx) = std::sync::mpsc::channel::<Promise<bool>>();
let status = callback.call_with_return_value(
Ok(SshUIRequest {
let promise_result: Result<Promise<bool>, napi::Error> = callback
.call_async(Ok(SshUIRequest {
cipher_id: request.cipher_id,
is_list: request.is_list,
process_name: request.process_name,
is_forwarding: request.is_forwarding,
namespace: request.namespace,
}),
ThreadsafeFunctionCallMode::Blocking,
move |ret: Result<Promise<bool>, napi::Error>, _env| {
if let Ok(p) = ret {
let _ = tx.send(p);
}))
.await;
match promise_result {
Ok(promise_result) => match promise_result.await {
Ok(result) => {
let _ = auth_response_tx_arc
.lock()
.await
.send((request.request_id, result))
.expect("should be able to send auth response to agent");
}
Ok(())
},
);
let result = if status == napi::Status::Ok {
match rx.recv() {
Ok(promise) => match promise.await {
Ok(v) => v,
Err(e) => {
error!(error = %e, "UI callback promise rejected");
false
}
},
Err(e) => {
error!(error = %e, "Failed to receive UI callback promise");
false
error!(error = %e, "Calling UI callback promise was rejected");
let _ = auth_response_tx_arc
.lock()
.await
.send((request.request_id, false))
.expect("should be able to send auth response to agent");
}
},
Err(e) => {
error!(error = %e, "Calling UI callback could not create promise");
let _ = auth_response_tx_arc
.lock()
.await
.send((request.request_id, false))
.expect("should be able to send auth response to agent");
}
} else {
error!(error = ?status, "Calling UI callback failed");
false
};
let _ = auth_response_tx_arc
.lock()
.await
.send((request.request_id, result))
.expect("should be able to send auth response to agent");
}
});
}
});
@@ -475,12 +465,14 @@ pub mod processisolations {
#[napi]
pub mod powermonitors {
use napi::{
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
threadsafe_function::{
ErrorStrategy::CalleeHandled, ThreadsafeFunction, ThreadsafeFunctionCallMode,
},
tokio,
};
#[napi]
pub async fn on_lock(callback: ThreadsafeFunction<()>) -> napi::Result<()> {
pub async fn on_lock(callback: ThreadsafeFunction<(), CalleeHandled>) -> napi::Result<()> {
let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(32);
desktop_core::powermonitor::on_lock(tx)
.await
@@ -519,7 +511,9 @@ pub mod windows_registry {
#[napi]
pub mod ipc {
use desktop_core::ipc::server::{Message, MessageType};
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi::threadsafe_function::{
ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode,
};
#[napi(object)]
pub struct IpcMessage {
@@ -556,12 +550,12 @@ pub mod ipc {
}
#[napi]
pub struct NativeIpcServer {
pub struct IpcServer {
server: desktop_core::ipc::server::Server,
}
#[napi]
impl NativeIpcServer {
impl IpcServer {
/// Create and start the IPC server without blocking.
///
/// @param name The endpoint name to listen on. This name uniquely identifies the IPC
@@ -572,7 +566,7 @@ pub mod ipc {
pub async fn listen(
name: String,
#[napi(ts_arg_type = "(error: null | Error, message: IpcMessage) => void")]
callback: ThreadsafeFunction<IpcMessage>,
callback: ThreadsafeFunction<IpcMessage, ErrorStrategy::CalleeHandled>,
) -> napi::Result<Self> {
let (send, mut recv) = tokio::sync::mpsc::channel::<Message>(32);
tokio::spawn(async move {
@@ -589,7 +583,7 @@ pub mod ipc {
))
})?;
Ok(NativeIpcServer { server })
Ok(IpcServer { server })
}
/// Return the path to the IPC server.
@@ -636,9 +630,8 @@ pub mod autostart {
#[napi]
pub mod autofill {
use desktop_core::ipc::server::{Message, MessageType};
use napi::{
bindgen_prelude::FnArgs,
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
use napi::threadsafe_function::{
ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tracing::error;
@@ -753,14 +746,14 @@ pub mod autofill {
}
#[napi]
pub struct AutofillIpcServer {
pub struct IpcServer {
server: desktop_core::ipc::server::Server,
}
// FIXME: Remove unwraps! They panic and terminate the whole application.
#[allow(clippy::unwrap_used)]
#[napi]
impl AutofillIpcServer {
impl IpcServer {
/// Create and start the IPC server without blocking.
///
/// @param name The endpoint name to listen on. This name uniquely identifies the IPC
@@ -776,24 +769,30 @@ pub mod autofill {
ts_arg_type = "(error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyRegistrationRequest) => void"
)]
registration_callback: ThreadsafeFunction<
FnArgs<(u32, u32, PasskeyRegistrationRequest)>,
(u32, u32, PasskeyRegistrationRequest),
ErrorStrategy::CalleeHandled,
>,
#[napi(
ts_arg_type = "(error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyAssertionRequest) => void"
)]
assertion_callback: ThreadsafeFunction<
FnArgs<(u32, u32, PasskeyAssertionRequest)>,
(u32, u32, PasskeyAssertionRequest),
ErrorStrategy::CalleeHandled,
>,
#[napi(
ts_arg_type = "(error: null | Error, clientId: number, sequenceNumber: number, message: PasskeyAssertionWithoutUserInterfaceRequest) => void"
)]
assertion_without_user_interface_callback: ThreadsafeFunction<
FnArgs<(u32, u32, PasskeyAssertionWithoutUserInterfaceRequest)>,
(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)>,
native_status_callback: ThreadsafeFunction<
(u32, u32, NativeStatus),
ErrorStrategy::CalleeHandled,
>,
) -> napi::Result<Self> {
let (send, mut recv) = tokio::sync::mpsc::channel::<Message>(32);
tokio::spawn(async move {
@@ -818,7 +817,7 @@ pub mod autofill {
Ok(msg) => {
let value = msg
.value
.map(|value| (client_id, msg.sequence_number, value).into())
.map(|value| (client_id, msg.sequence_number, value))
.map_err(|e| napi::Error::from_reason(format!("{e:?}")));
assertion_callback
@@ -837,7 +836,7 @@ pub mod autofill {
Ok(msg) => {
let value = msg
.value
.map(|value| (client_id, msg.sequence_number, value).into())
.map(|value| (client_id, msg.sequence_number, value))
.map_err(|e| napi::Error::from_reason(format!("{e:?}")));
assertion_without_user_interface_callback
@@ -855,7 +854,7 @@ pub mod autofill {
Ok(msg) => {
let value = msg
.value
.map(|value| (client_id, msg.sequence_number, value).into())
.map(|value| (client_id, msg.sequence_number, value))
.map_err(|e| napi::Error::from_reason(format!("{e:?}")));
registration_callback
.call(value, ThreadsafeFunctionCallMode::NonBlocking);
@@ -895,7 +894,7 @@ pub mod autofill {
))
})?;
Ok(AutofillIpcServer { server })
Ok(IpcServer { server })
}
/// Return the path to the IPC server.
@@ -988,9 +987,8 @@ pub mod logging {
use std::{fmt::Write, sync::OnceLock};
use napi::{
bindgen_prelude::FnArgs,
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
use napi::threadsafe_function::{
ErrorStrategy::CalleeHandled, ThreadsafeFunction, ThreadsafeFunctionCallMode,
};
use tracing::Level;
use tracing_subscriber::{
@@ -1001,7 +999,7 @@ pub mod logging {
Layer,
};
struct JsLogger(OnceLock<ThreadsafeFunction<FnArgs<(LogLevel, String)>>>);
struct JsLogger(OnceLock<ThreadsafeFunction<(LogLevel, String), CalleeHandled>>);
static JS_LOGGER: JsLogger = JsLogger(OnceLock::new());
#[napi]
@@ -1073,13 +1071,13 @@ pub mod logging {
let msg = (event.metadata().level().into(), buffer);
if let Some(logger) = JS_LOGGER.0.get() {
let _ = logger.call(Ok(msg.into()), ThreadsafeFunctionCallMode::NonBlocking);
let _ = logger.call(Ok(msg), ThreadsafeFunctionCallMode::NonBlocking);
};
}
}
#[napi]
pub fn init_napi_log(js_log_fn: ThreadsafeFunction<FnArgs<(LogLevel, String)>>) {
pub fn init_napi_log(js_log_fn: ThreadsafeFunction<(LogLevel, String), CalleeHandled>) {
let _ = JS_LOGGER.0.set(js_log_fn);
// the log level hierarchy is determined by:
@@ -1150,8 +1148,8 @@ pub mod chromium_importer {
#[napi(object)]
pub struct NativeImporterMetadata {
pub id: String,
pub loaders: Vec<String>,
pub instructions: String,
pub loaders: Vec<&'static str>,
pub instructions: &'static str,
}
impl From<_LoginImportResult> for LoginImportResult {
@@ -1228,7 +1226,7 @@ pub mod chromium_importer {
#[napi]
pub mod autotype {
#[napi]
pub fn get_foreground_window_title() -> napi::Result<String> {
pub fn get_foreground_window_title() -> napi::Result<String, napi::Status> {
autotype::get_foreground_window_title().map_err(|_| {
napi::Error::from_reason(
"Autotype Error: failed to get foreground window title".to_string(),

View File

@@ -37,7 +37,7 @@ export class MainSshAgentService {
init() {
// handle sign request passing to UI
sshagent
.serve(async (err: Error | null, sshUiRequest: sshagent.SshUiRequest): Promise<boolean> => {
.serve(async (err: Error, sshUiRequest: sshagent.SshUiRequest) => {
// clear all old (> SIGN_TIMEOUT) requests
this.requestResponses = this.requestResponses.filter(
(response) => response.timestamp > new Date(Date.now() - this.SIGN_TIMEOUT),

View File

@@ -14,7 +14,7 @@ import { isDev } from "../utils";
import { WindowMain } from "./window.main";
export class NativeMessagingMain {
private ipcServer: ipc.NativeIpcServer | null;
private ipcServer: ipc.IpcServer | null;
private connected: number[] = [];
constructor(
@@ -78,7 +78,7 @@ export class NativeMessagingMain {
this.ipcServer.stop();
}
this.ipcServer = await ipc.NativeIpcServer.listen("bw", (error, msg) => {
this.ipcServer = await ipc.IpcServer.listen("bw", (error, msg) => {
switch (msg.kind) {
case ipc.IpcMessageType.Connected: {
this.connected.push(msg.clientId);

View File

@@ -21,7 +21,7 @@ export type RunCommandParams<C extends CommandDefinition> = {
export type RunCommandResult<C extends CommandDefinition> = C["output"];
export class NativeAutofillMain {
private ipcServer?: autofill.AutofillIpcServer;
private ipcServer: autofill.IpcServer | null;
private messageBuffer: BufferedMessage[] = [];
private listenerReady = false;
@@ -70,13 +70,13 @@ export class NativeAutofillMain {
},
);
this.ipcServer = await autofill.AutofillIpcServer.listen(
this.ipcServer = await autofill.IpcServer.listen(
"af",
// RegistrationCallback
(error, clientId, sequenceNumber, request) => {
if (error) {
this.logService.error("autofill.IpcServer.registration", error);
this.ipcServer?.completeError(clientId, sequenceNumber, String(error));
this.ipcServer.completeError(clientId, sequenceNumber, String(error));
return;
}
this.safeSend("autofill.passkeyRegistration", {
@@ -89,7 +89,7 @@ export class NativeAutofillMain {
(error, clientId, sequenceNumber, request) => {
if (error) {
this.logService.error("autofill.IpcServer.assertion", error);
this.ipcServer?.completeError(clientId, sequenceNumber, String(error));
this.ipcServer.completeError(clientId, sequenceNumber, String(error));
return;
}
this.safeSend("autofill.passkeyAssertion", {
@@ -102,7 +102,7 @@ export class NativeAutofillMain {
(error, clientId, sequenceNumber, request) => {
if (error) {
this.logService.error("autofill.IpcServer.assertion", error);
this.ipcServer?.completeError(clientId, sequenceNumber, String(error));
this.ipcServer.completeError(clientId, sequenceNumber, String(error));
return;
}
this.safeSend("autofill.passkeyAssertionWithoutUserInterface", {
@@ -115,7 +115,7 @@ export class NativeAutofillMain {
(error, clientId, sequenceNumber, status) => {
if (error) {
this.logService.error("autofill.IpcServer.nativeStatus", error);
this.ipcServer?.completeError(clientId, sequenceNumber, String(error));
this.ipcServer.completeError(clientId, sequenceNumber, String(error));
return;
}
this.safeSend("autofill.nativeStatus", {
@@ -137,19 +137,19 @@ export class NativeAutofillMain {
ipcMain.on("autofill.completePasskeyRegistration", (event, data) => {
this.logService.debug("autofill.completePasskeyRegistration", data);
const { clientId, sequenceNumber, response } = data;
this.ipcServer?.completeRegistration(clientId, sequenceNumber, response);
this.ipcServer.completeRegistration(clientId, sequenceNumber, response);
});
ipcMain.on("autofill.completePasskeyAssertion", (event, data) => {
this.logService.debug("autofill.completePasskeyAssertion", data);
const { clientId, sequenceNumber, response } = data;
this.ipcServer?.completeAssertion(clientId, sequenceNumber, response);
this.ipcServer.completeAssertion(clientId, sequenceNumber, response);
});
ipcMain.on("autofill.completeError", (event, data) => {
this.logService.debug("autofill.completeError", data);
const { clientId, sequenceNumber, error } = data;
this.ipcServer?.completeError(clientId, sequenceNumber, String(error));
this.ipcServer.completeError(clientId, sequenceNumber, String(error));
});
}

1479
package-lock.json generated

File diff suppressed because it is too large Load Diff