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
4 changes: 4 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 26 additions & 6 deletions docs/content/docs/guides/bare-host.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import { Callout } from 'fumadocs-ui/components/callout';

RNQC 2.0 is generated for Nitro Modules v1 with nitrogen's `bare` environment. The same package runs in a React Native 0.88+ app and in any host that provides a `jsi::Runtime`, such as Hermes embedded without React Native.

<Callout type="warn">
Bare-host support is new in RNQC 2.0. The native link was verified against
Nitro Modules v1's standalone test runner (Hermes, no React Native): the Apple
build links with no duplicate symbols and hashes `sha256("abc")` correctly in
the simulator, and the Android library builds against the `nitro-core` prefab.
A full bare-host smoke test is still tracked in #1104.
<Callout type="info">
The repository verifies bare-host support on every platform it ships:
`scripts/bare-host.sh ios` and `scripts/bare-host.sh android` run a smoke
test (hash including `multiformats` SHA-2, AES-256-GCM, Ed25519 and P-256
sign/verify, random) inside Nitro Modules v1's standalone test runner
(Hermes, no React Native). Verified on the arm64 iOS simulator and an arm64-v8a
Android API 35 emulator, Debug builds. See [Verified setup](#verified-setup).
</Callout>

## Install
Expand Down Expand Up @@ -86,6 +87,8 @@ Hermes does not support async generators, so run your bundle through a transform

The shared entry uses `@craftzdog/react-native-buffer`. Off React Native it uses `base64-js`, but your bundler still has to resolve its React Native branch. Alias `react-native-quick-base64` to `base64-js` in your bundler. The shared entry also imports `util` and `string_decoder`, so your host needs polyfills for them.

If your bundler honors the `browser` condition, packages such as `multiformats` resolve to builds that call `crypto.subtle` instead of `createHash`. Alias those subpaths to their Node builds if you want them to use RNQC's `crypto` export.

```ts
import { createHash, install } from 'react-native-quick-crypto';

Expand All @@ -95,3 +98,20 @@ createHash('sha256').update('abc').digest('hex');
```

The `react-native` condition selects an entry that imports `react-native-nitro-modules` and `react-native-quick-base64` first. In a bare host, `install()` doesn't set the `base64ToArrayBuffer` or `base64FromArrayBuffer` globals.

The shared entry exports an ES module namespace. A CommonJS `require('react-native-quick-crypto')` therefore returns the namespace object, whose properties are read-only getters; property reads and `install()` behave as before, but assigning to the returned object no longer works.

## Verified setup

`scripts/bare-host.sh ios|android` is the reference recipe. Each mode clones `margelo/nitro` at the commit behind RNQC's pinned Nitro peer version into `build/bare-host/nitro`, applies the patch in `example/test/bare/host`, copies RNQC's shipped native files in, bundles `example/test/bare`, builds, runs, and writes `build/bare-host/result-<platform>.txt` (`BARE_HOST_RESULT PASS` or `FAIL`).

- **iOS:** builds the runner with RNQC as a local Swift package and runs it on an arm64 simulator (set `BARE_HOST_IOS_OS` or `--os` to pick the runtime).
- **Android:** builds a Gradle module around `android/CMakeLists.txt`, runs `connectedDebugAndroidTest` on an arm64-v8a emulator, and fails the result if `libQuickCrypto.so` exports `EVP_`, `ERR_` or `SSL_` symbols. It boots its own AVD on port 5584 unless `ANDROID_SERIAL` names a device.

The pieces a bare host needs, as the script wires them:

1. `margelo::nitro::install(runtime, dispatcher)` before any JavaScript loads RNQC.
2. Registration: `System.loadLibrary("QuickCrypto")` on Android after Nitro core is loaded, and a single `registerHybridClasses()` call on Apple (guard it with `std::call_once` if the runtime is created more than once).
3. A bundle with `react-native-quick-base64` aliased to `base64-js`.
4. A prelude that defines the globals bare Hermes lacks: `global`, `self`, `console`, `AbortController`/`AbortSignal`, and `kCustomPromisifiedSymbol` (read by the bundled `util` polyfill). See `example/test/bare/prelude.ts`.
5. An async-generator transform (`@babel/plugin-transform-async-generator-functions`) over the finished bundle, because Hermes rejects async generators and `for await`. See `example/test/bare/host/hermes-transform.mjs`.
2 changes: 2 additions & 0 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
},
"devDependencies": {
"@babel/core": "7.28.4",
"@babel/plugin-transform-async-generator-functions": "7.29.0",
"@babel/plugin-transform-class-static-block": "7.26.0",
"@babel/preset-env": "7.26.0",
"@babel/preset-typescript": "7.28.5",
Expand All @@ -74,6 +75,7 @@
"babel-plugin-module-resolver": "5.0.2",
"hermes-compiler": "260318099.0.5",
"jose": "6.1.3",
"multiformats": "13.4.2",
"react-test-renderer": "19.3.0",
"typescript": "5.8.3"
},
Expand Down
31 changes: 31 additions & 0 deletions example/test/bare/aliases.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { fileURLToPath } from 'node:url';

const rnqcEntry = fileURLToPath(
new URL(
'../../../packages/react-native-quick-crypto/src/index.ts',
import.meta.url,
),
);
const aliases = {
'react-native-quick-base64': fileURLToPath(import.meta.resolve('base64-js')),
'react-native-quick-crypto': rnqcEntry,
crypto: rnqcEntry,
'node:crypto': rnqcEntry,
// The bundler's "browser" condition would pick multiformats' WebCrypto build;
// resolving from Node/Bun here picks its Node build, which imports `crypto`
// (aliased to RNQC above).
'multiformats/hashes/sha2': fileURLToPath(
import.meta.resolve('multiformats/hashes/sha2'),
),
};

// Bun bundler plugin used by the bare-host driver (scripts/bare-host.sh).
export const aliasPlugin = {
name: 'rnqc-bare-aliases',
setup(build) {
build.onResolve({ filter: /.*/ }, ({ path }) => {
const target = aliases[path];
return target === undefined ? undefined : { path: target };
});
},
};
40 changes: 40 additions & 0 deletions example/test/bare/host/android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.android'
}

android {
namespace 'com.margelo.nitro.quickcrypto'
compileSdk providers.gradleProperty('nitroTestCompileSdk').get().toInteger()
ndkVersion providers.gradleProperty('nitroTestNdkVersion').get()

defaultConfig {
minSdk providers.gradleProperty('nitroTestMinSdk').get().toInteger()
ndk { abiFilters providers.gradleProperty('nitroTestAbi').get() }
externalNativeBuild {
cmake {
cppFlags '-frtti -fexceptions -Wall -fstack-protector-all'
arguments '-DANDROID_STL=c++_shared', '-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON', "-DCMAKE_PROJECT_INCLUDE=${projectDir}/host-hermes.cmake"
targets 'QuickCrypto'
}
}
}
buildFeatures { prefab true }
externalNativeBuild {
cmake {
path 'CMakeLists.txt'
version providers.gradleProperty('nitroTestCmakeVersion').get()
}
}
sourceSets { main { java.srcDirs = [] } }
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions { jvmTarget = '17' }
}

dependencies {
api project(':nitro-core')
implementation 'io.github.ronickg:openssl-static:3.6.2-3'
}
2 changes: 2 additions & 0 deletions example/test/bare/host/android/host-hermes.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
find_package(hermes REQUIRED CONFIG)
cmake_language(DEFER DIRECTORY "${CMAKE_SOURCE_DIR}" CALL target_link_libraries QuickCrypto hermes::hermesvm)
22 changes: 22 additions & 0 deletions example/test/bare/host/hermes-transform.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Hermes lacks async generators and `for await` (Metro transforms them for
// React Native); the bundled stream polyfills use both. Lower just those so a
// bare Hermes host can evaluate the bundle.
import { createRequire } from 'node:module';
import { readFileSync, writeFileSync } from 'node:fs';

const require = createRequire(import.meta.url);
const babel = require('@babel/core');

const [file] = process.argv.slice(2);
if (file === undefined)
throw new Error('usage: hermes-transform.mjs <bundle.js>');
const result = babel.transformSync(readFileSync(file, 'utf8'), {
filename: file,
babelrc: false,
configFile: false,
compact: false,
sourceMaps: false,
plugins: [require('@babel/plugin-transform-async-generator-functions')],
});
writeFileSync(file, result.code);
console.log(`Transformed ${file} for Hermes`);
108 changes: 108 additions & 0 deletions example/test/bare/host/rnqc-overlay.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
diff --git a/Package.swift b/Package.swift
index 56e1b6a..d8b584c 100644
--- a/Package.swift
+++ b/Package.swift
@@ -27,6 +27,7 @@ let package = Package(
.library(name: "NitroTestRunnerBridge", targets: ["NitroTestRunnerBridge"])
],
dependencies: [
+ .package(path: "tests/standalone/quick-crypto"),
.package(
url: "https://github.com/margelo/simdutf-swift.git",
from: "1.1.0",
@@ -96,6 +97,7 @@ package.targets += [
dependencies: [
"Hermes", "NitroModulesCxx", "NitroModulesSwiftBridge",
"NitroTestSwiftBridge", "NitroTestExternalSwiftBridge",
+ .product(name: "QuickCrypto", package: "quick-crypto"),
],
path: "tests/standalone/test-runner/cpp",
publicHeadersPath: ".",
diff --git a/tests/standalone/test-runner/android/build.gradle b/tests/standalone/test-runner/android/build.gradle
index 86f9aa1..2f1716a 100644
--- a/tests/standalone/test-runner/android/build.gradle
+++ b/tests/standalone/test-runner/android/build.gradle
@@ -99,6 +99,7 @@ dependencies {
implementation project(':hermes')
implementation project(':nitro-core')
implementation project(':nitro-test')
+ implementation project(':quick-crypto')

androidTestImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.7.0'
diff --git a/tests/standalone/test-runner/android/settings.gradle b/tests/standalone/test-runner/android/settings.gradle
index fe7596f..b2122ab 100644
--- a/tests/standalone/test-runner/android/settings.gradle
+++ b/tests/standalone/test-runner/android/settings.gradle
@@ -15,8 +15,9 @@ dependencyResolutionManagement {
}

rootProject.name = 'NitroTestRunner'
-include ':hermes', ':nitro-core', ':nitro-test', ':nitro-test-external'
+include ':hermes', ':quick-crypto', ':nitro-core', ':nitro-test', ':nitro-test-external'
project(':hermes').projectDir = file('../../hermes/android')
project(':nitro-core').projectDir = file('../../nitro-core/android')
project(':nitro-test-external').projectDir = file('../../nitro-test-external/android')
project(':nitro-test').projectDir = file('../../nitro-test/android')
+project(':quick-crypto').projectDir = file('../../quick-crypto/android')
diff --git a/tests/standalone/test-runner/android/src/main/java/com/margelo/nitro/testing/runner/NativeTestRuntime.kt b/tests/standalone/test-runner/android/src/main/java/com/margelo/nitro/testing/runner/NativeTestRuntime.kt
index 99f114c..1915f95 100644
--- a/tests/standalone/test-runner/android/src/main/java/com/margelo/nitro/testing/runner/NativeTestRuntime.kt
+++ b/tests/standalone/test-runner/android/src/main/java/com/margelo/nitro/testing/runner/NativeTestRuntime.kt
@@ -5,6 +5,7 @@ import com.margelo.nitro.test.NitroTest
internal object NativeTestRuntime {
init {
NitroTest.initialize()
+ System.loadLibrary("QuickCrypto")
System.loadLibrary("NitroTestRunner")
}

diff --git a/tests/standalone/test-runner/cpp/TestRuntime.cpp b/tests/standalone/test-runner/cpp/TestRuntime.cpp
index d819309..d75a832 100644
--- a/tests/standalone/test-runner/cpp/TestRuntime.cpp
+++ b/tests/standalone/test-runner/cpp/TestRuntime.cpp
@@ -6,6 +6,9 @@

#include <NitroModules/Dispatcher.hpp>
#include <NitroModules/InstallNitro.hpp>
+#ifndef __ANDROID__
+#include <QuickCrypto/QuickCryptoAutolinking.hpp>
+#endif
#include <chrono>
#include <cmath>
#include <condition_variable>
@@ -180,6 +183,10 @@ namespace {
auto prepared = prepareBundle(*runtime, bundle);
phase = "installing Nitro";
install(*runtime, dispatcher);
+#ifndef __ANDROID__
+ static std::once_flag quickCryptoOnce;
+ std::call_once(quickCryptoOnce, [] { margelo::nitro::crypto::registerHybridClasses(); });
+#endif
// Expose platform information and explicit garbage collection to the tests.
#ifdef __ANDROID__
runtime->global().setProperty(*runtime, "__nitroTestPlatform", "android");
diff --git a/tests/standalone/test-runner/ios/build.mjs b/tests/standalone/test-runner/ios/build.mjs
index 043402f..2c76672 100644
--- a/tests/standalone/test-runner/ios/build.mjs
+++ b/tests/standalone/test-runner/ios/build.mjs
@@ -66,6 +66,7 @@ const status = await xcodebuild(
'-jobs',
String(jobs),
'CODE_SIGNING_ALLOWED=NO',
+ `OTHER_CPLUSPLUSFLAGS=$(inherited) -I${root}/packages/nitro-core/native/cpp/include -I${root}/tests/standalone/.build/hermes/NitroTestHermes.xcframework/ios-arm64-simulator/Headers`,
`ARCHS=${architecture}`,
`IPHONEOS_DEPLOYMENT_TARGET=${defaults.deploymentTarget}`,
],
diff --git a/tests/standalone/test-runner/scripts/bundle.ts b/tests/standalone/test-runner/scripts/bundle.ts
index 22ca26e..561e6c1 100644
--- a/tests/standalone/test-runner/scripts/bundle.ts
+++ b/tests/standalone/test-runner/scripts/bundle.ts
@@ -97,6 +97,7 @@ const result = await Bun.build({
format: 'iife',
sourcemap: 'external',
minify: false,
+ plugins: process.env.RNQC_BARE_ALIASES ? [(await import(process.env.RNQC_BARE_ALIASES)).aliasPlugin] : [],
})
if (!result.success) throw new AggregateError(result.logs, 'Test bundle failed')
await Bun.write(`${root}build/runtime-tests.json`, `${JSON.stringify(suites, null, 2)}\n`)
45 changes: 45 additions & 0 deletions example/test/bare/prelude.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Globals a bare Hermes host lacks.
const root = globalThis as Record<string, unknown>;
root.global ??= globalThis;
root.self ??= globalThis;
// Bare Hermes has no console (nitro-core warns through it on a version skew).
const noop = (): void => {};
root.console ??= {
log: noop,
info: noop,
warn: noop,
error: noop,
debug: noop,
};

// React Native supplies AbortController; a bare Hermes host does not, and the
// bundled stream polyfills read it at load time. Minimal, listener-only version.
type AbortListener = () => void;
class StubAbortSignal {
aborted = false;
reason: unknown = undefined;
private listeners: AbortListener[] = [];
addEventListener(_type: string, listener: AbortListener): void {
this.listeners.push(listener);
}
removeEventListener(_type: string, listener: AbortListener): void {
this.listeners = this.listeners.filter(l => l !== listener);
}
abort(reason: unknown): void {
if (this.aborted) return;
this.aborted = true;
this.reason = reason;
this.listeners.forEach(l => l());
}
}
class StubAbortController {
signal = new StubAbortSignal();
abort(reason?: unknown): void {
this.signal.abort(reason);
}
}
root.AbortSignal ??= StubAbortSignal;
root.AbortController ??= StubAbortController;

// Bun's browser-target `util` polyfill reads this as an implicit global.
root.kCustomPromisifiedSymbol ??= Symbol.for('nodejs.util.promisify.custom');
Loading