Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/desktop-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,15 @@ jobs:
bunx electron-builder --mac dir --universal --publish never \
-c.mac.identity=- -c.mac.hardenedRuntime=false

# Reads an item from a throwaway keychain it puts on the search list, so it
# stays in CI. A Keychain prompt would block headlessly; the timeout fails it fast.
- name: Read a throwaway Keychain item through the native addon
working-directory: apps/desktop
timeout-minutes: 3
env:
SIM_KEYCHAIN_ITEM_TEST: '1'
run: bunx vitest run src/main/browser-import/keychain-native.test.ts

- name: Run packaged Electron smoke suite
working-directory: apps/desktop
run: |
Expand Down
13 changes: 12 additions & 1 deletion apps/desktop/e2e/packaged-smoke.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { spawn } from 'node:child_process'
import { existsSync, mkdtempSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { dirname, join } from 'node:path'
import { FuseV1Options, FuseVersion, getCurrentFuseWire } from '@electron/fuses'
import { type Browser, chromium } from '@playwright/test'
import { expect, stopAndRemoveProfile, test } from './harness'
Expand Down Expand Up @@ -43,6 +43,17 @@ test('packaged Electron binary has the production fuse policy', async () => {
}
})

// Native addons cannot be dlopen'd from inside app.asar; one left packed fails
// only when the feature that loads it runs (the Keychain one, during an import).
test('packaged app ships every native addon outside the asar', () => {
const executablePath = process.env.SIM_DESKTOP_EXECUTABLE
if (!executablePath) throw new Error('SIM_DESKTOP_EXECUTABLE is required')
const unpacked = join(dirname(executablePath), '..', 'Resources', 'app.asar.unpacked')
for (const addon of ['directory', 'help-search', 'keychain']) {
expect(existsSync(join(unpacked, 'dist', 'native', `${addon}.node`)), addon).toBe(true)
}
})

// The unpackaged suite cannot see this: the bundled pages live inside app.asar
// only once packaged, and the file-protocol fuse is only off once packaged.
// v0.8.13 through v0.8.19 shipped both pages blank because nothing loaded them
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/electron-builder.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ extraResources:

asar: true

# Native modules cannot be dlopen'd from inside an asar. The Help-search addon
# is already universal; `scripts/ensure-pty-prebuilds.ts` guarantees both pty
# Native modules cannot be dlopen'd from inside an asar. The native addons are
# already universal; `scripts/ensure-pty-prebuilds.ts` guarantees both pty
# prebuilds are present before packaging.
asarUnpack:
- "**/node_modules/@lydell/node-pty-*/prebuilds/**"
Expand Down
210 changes: 210 additions & 0 deletions apps/desktop/native/keychain.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// memset_s is the C11 Annex K wipe the optimizer may not elide; string.h only declares it on request.
#define __STDC_WANT_LIB_EXT1__ 1

#import <Foundation/Foundation.h>
#import <Security/Security.h>

#include <node_api.h>

#include <string.h>

#include <iterator>
#include <string>
#include <vector>

/**
* Reads a generic-password Keychain item inside the Sim process, so the
* Keychain prompt names Sim and "Always Allow" trusts Sim rather than a shared
* system tool that any other process could run. Nothing here caches a secret:
* each read copies the password into JS and wipes the buffer it owns.
*/

enum class ReadStatus { kFound, kMissing, kDenied, kFailed };

struct ReadRequest {
std::string service;
std::string account;
std::vector<char> password;
ReadStatus status = ReadStatus::kFailed;
OSStatus os_status = errSecSuccess;
napi_deferred deferred = nullptr;
napi_async_work work = nullptr;
};

static void Wipe(std::vector<char>* buffer) {
if (!buffer->empty()) {
memset_s(buffer->data(), buffer->size(), 0, buffer->size());
}
buffer->clear();
}

static NSString* StringFromUTF8(const std::string& value) {
return [[NSString alloc] initWithBytes:value.data()
length:value.size()
encoding:NSUTF8StringEncoding];
}

static ReadStatus StatusFor(OSStatus status) {
switch (status) {
case errSecItemNotFound:
return ReadStatus::kMissing;
case errSecUserCanceled:
case errSecAuthFailed:
case errSecInteractionNotAllowed:
return ReadStatus::kDenied;
default:
return ReadStatus::kFailed;
}
}

/** Runs off the JS thread: the call blocks for as long as the user sits on the Keychain prompt. */
static void ExecuteRead(napi_env env, void* data) {
(void)env;
ReadRequest* request = static_cast<ReadRequest*>(data);
@autoreleasepool {
NSString* service = StringFromUTF8(request->service);
NSString* account = StringFromUTF8(request->account);
if (!service || !account) {
request->status = ReadStatus::kFailed;
request->os_status = errSecParam;
return;
}
NSDictionary* query = @{
(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService : service,
(__bridge id)kSecAttrAccount : account,
(__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitOne,
(__bridge id)kSecReturnData : @YES,
};
CFTypeRef result = nullptr;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
request->os_status = status;
if (status == errSecSuccess) {
if (result && CFGetTypeID(result) == CFDataGetTypeID()) {
CFDataRef password = static_cast<CFDataRef>(result);
CFIndex length = CFDataGetLength(password);
if (length > 0) {
request->password.resize(static_cast<size_t>(length));
CFDataGetBytes(password, CFRangeMake(0, length),
reinterpret_cast<UInt8*>(request->password.data()));
}
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
request->status = ReadStatus::kFound;
} else {
request->status = ReadStatus::kFailed;
}
} else {
request->status = StatusFor(status);
}
if (result) {
CFRelease(result);
}
}
}

static const char* StatusName(ReadStatus status) {
switch (status) {
case ReadStatus::kFound:
return "found";
case ReadStatus::kMissing:
return "missing";
case ReadStatus::kDenied:
return "denied";
case ReadStatus::kFailed:
return "failed";
}
return "failed";
}

static void SetString(napi_env env, napi_value object, const char* name, const char* value,
size_t length) {
napi_value string;
napi_create_string_utf8(env, value, length, &string);
napi_set_named_property(env, object, name, string);
}

static void CompleteRead(napi_env env, napi_status status, void* data) {
ReadRequest* request = static_cast<ReadRequest*>(data);
if (status == napi_ok) {
napi_value result;
napi_create_object(env, &result);
SetString(env, result, "status", StatusName(request->status), NAPI_AUTO_LENGTH);
if (request->status == ReadStatus::kFound) {
SetString(env, result, "password", request->password.data(), request->password.size());
} else {
napi_value code;
napi_create_int32(env, request->os_status, &code);
napi_set_named_property(env, result, "code", code);
}
napi_resolve_deferred(env, request->deferred, result);
} else {
napi_value message;
napi_value error;
napi_create_string_utf8(env, "Keychain read was cancelled", NAPI_AUTO_LENGTH, &message);
napi_create_error(env, nullptr, message, &error);
napi_reject_deferred(env, request->deferred, error);
}
Wipe(&request->password);
napi_delete_async_work(env, request->work);
delete request;
}

static bool ReadString(napi_env env, napi_value value, const char* name, std::string* output) {
napi_valuetype type;
size_t length = 0;
if (napi_typeof(env, value, &type) != napi_ok || type != napi_string ||
napi_get_value_string_utf8(env, value, nullptr, 0, &length) != napi_ok) {
std::string message = std::string(name) + " must be a string";
napi_throw_type_error(env, nullptr, message.c_str());
return false;
}
std::vector<char> buffer(length + 1);
if (napi_get_value_string_utf8(env, value, buffer.data(), buffer.size(), &length) != napi_ok) {
std::string message = std::string("could not read ") + name;
napi_throw_type_error(env, nullptr, message.c_str());
return false;
}
output->assign(buffer.data(), length);
return true;
}

/** `readGenericPassword(service, account)` resolves `{ status, password?, code? }`. */
static napi_value ReadGenericPassword(napi_env env, napi_callback_info info) {
size_t argument_count = 2;
napi_value arguments[2];
if (napi_get_cb_info(env, info, &argument_count, arguments, nullptr, nullptr) != napi_ok ||
argument_count != 2) {
napi_throw_type_error(env, nullptr, "readGenericPassword expects a service and an account");
return nullptr;
}
ReadRequest* request = new ReadRequest();
if (!ReadString(env, arguments[0], "service", &request->service) ||
!ReadString(env, arguments[1], "account", &request->account)) {
delete request;
return nullptr;
}
napi_value promise;
napi_value resource_name;
if (napi_create_promise(env, &request->deferred, &promise) != napi_ok ||
napi_create_string_utf8(env, "SimKeychainRead", NAPI_AUTO_LENGTH, &resource_name) !=
napi_ok ||
napi_create_async_work(env, nullptr, resource_name, ExecuteRead, CompleteRead, request,
&request->work) != napi_ok ||
napi_queue_async_work(env, request->work) != napi_ok) {
if (request->work) {
napi_delete_async_work(env, request->work);
}
delete request;
napi_throw_error(env, nullptr, "could not start the Keychain read");
return nullptr;
}
return promise;
}

NAPI_MODULE_INIT() {
napi_property_descriptor properties[] = {
{"readGenericPassword", nullptr, ReadGenericPassword, nullptr, nullptr, nullptr,
napi_default, nullptr},
};
napi_define_properties(env, exports, std::size(properties), properties);
return exports;
}
21 changes: 16 additions & 5 deletions apps/desktop/scripts/build-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,17 @@ if (process.platform !== 'darwin' && process.platform !== 'linux') {
const includeDirectory = nodeIncludeDirectory()
const outputDirectory = 'dist/native'
mkdirSync(outputDirectory, { recursive: true })
const modules = [
{ name: 'directory', source: 'native/directory.cc', appKit: false },
const modules: { name: string; source: string; frameworks: string[] }[] = [
{ name: 'directory', source: 'native/directory.cc', frameworks: [] },
...(process.platform === 'darwin'
? [{ name: 'help-search', source: 'native/help-search.mm', appKit: true }]
? [
{
name: 'help-search',
source: 'native/help-search.mm',
frameworks: ['AppKit', 'Foundation'],
},
{ name: 'keychain', source: 'native/keychain.mm', frameworks: ['Security', 'Foundation'] },
]
: []),
]
for (const module of modules) {
Expand Down Expand Up @@ -61,8 +68,12 @@ for (const module of modules) {
: ['-shared', '-fPIC']),
'-I',
includeDirectory,
...(module.appKit
? ['-fobjc-arc', '-fblocks', '-framework', 'AppKit', '-framework', 'Foundation']
...(module.frameworks.length > 0
? [
'-fobjc-arc',
'-fblocks',
...module.frameworks.flatMap((framework) => ['-framework', framework]),
]
: []),
'-o',
output,
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/scripts/native-build-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ interface NativeOutput {
const SOURCES = [
'native/directory.cc',
'native/help-search.mm',
'native/keychain.mm',
'native/computer-use/ComputerUse.swift',
'native/computer-use/Info.plist',
'scripts/build.ts',
Expand Down
Loading
Loading