diff --git a/bun.lock b/bun.lock index cbab8f68..7b276c8b 100644 --- a/bun.lock +++ b/bun.lock @@ -59,6 +59,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", @@ -81,6 +82,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", }, @@ -1881,6 +1883,8 @@ "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "multiformats": ["multiformats@13.4.2", "", {}, "sha512-eh6eHCrRi1+POZ3dA+Dq1C6jhP1GNtr9CRINMb67OKzqW9I5DUuZM/3jLPlzhgpGeiNUlEGEbkCYChXMCc/8DQ=="], + "mute-stream": ["mute-stream@3.0.0", "", {}, "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw=="], "mz": ["mz@2.7.0", "", { "dependencies": { "any-promise": "^1.0.0", "object-assign": "^4.0.1", "thenify-all": "^1.0.0" } }, "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q=="], diff --git a/docs/content/docs/guides/bare-host.mdx b/docs/content/docs/guides/bare-host.mdx index 69548d0f..378c4038 100644 --- a/docs/content/docs/guides/bare-host.mdx +++ b/docs/content/docs/guides/bare-host.mdx @@ -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. - - 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. + + 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). ## Install @@ -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'; @@ -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-.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`. diff --git a/example/package.json b/example/package.json index 3fa28753..59264fc2 100644 --- a/example/package.json +++ b/example/package.json @@ -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", @@ -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" }, diff --git a/example/test/bare/aliases.mjs b/example/test/bare/aliases.mjs new file mode 100644 index 00000000..cb9efc47 --- /dev/null +++ b/example/test/bare/aliases.mjs @@ -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 }; + }); + }, +}; diff --git a/example/test/bare/host/android/build.gradle b/example/test/bare/host/android/build.gradle new file mode 100644 index 00000000..9d611be7 --- /dev/null +++ b/example/test/bare/host/android/build.gradle @@ -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' +} diff --git a/example/test/bare/host/android/host-hermes.cmake b/example/test/bare/host/android/host-hermes.cmake new file mode 100644 index 00000000..e9fdb601 --- /dev/null +++ b/example/test/bare/host/android/host-hermes.cmake @@ -0,0 +1,2 @@ +find_package(hermes REQUIRED CONFIG) +cmake_language(DEFER DIRECTORY "${CMAKE_SOURCE_DIR}" CALL target_link_libraries QuickCrypto hermes::hermesvm) diff --git a/example/test/bare/host/hermes-transform.mjs b/example/test/bare/host/hermes-transform.mjs new file mode 100644 index 00000000..9a6e276d --- /dev/null +++ b/example/test/bare/host/hermes-transform.mjs @@ -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 '); +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`); diff --git a/example/test/bare/host/rnqc-overlay.patch b/example/test/bare/host/rnqc-overlay.patch new file mode 100644 index 00000000..5283cbba --- /dev/null +++ b/example/test/bare/host/rnqc-overlay.patch @@ -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 + #include ++#ifndef __ANDROID__ ++#include ++#endif + #include + #include + #include +@@ -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`) diff --git a/example/test/bare/prelude.ts b/example/test/bare/prelude.ts new file mode 100644 index 00000000..193095d2 --- /dev/null +++ b/example/test/bare/prelude.ts @@ -0,0 +1,45 @@ +// Globals a bare Hermes host lacks. +const root = globalThis as Record; +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'); diff --git a/example/test/bare/quick-crypto.test.ts b/example/test/bare/quick-crypto.test.ts new file mode 100644 index 00000000..106c47f0 --- /dev/null +++ b/example/test/bare/quick-crypto.test.ts @@ -0,0 +1,198 @@ +import { expect } from 'chai'; +import { sha256, sha512 } from 'multiformats/hashes/sha2'; +import { + Buffer, + createDecipheriv, + createCipheriv, + createHash, + getRandomValues, + randomBytes, + randomFillSync, + sign, + verify, + generateKeyPairSync, + createSign, + createVerify, +} from 'react-native-quick-crypto'; + +const hex = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex'); + +const SHA256_EMPTY = + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; +const SHA256_ABC = + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'; +const SHA512_ABC = + 'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a' + + '2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f'; + +function abcSlice(): Uint8Array { + return new Uint8Array(Buffer.from('xxabcxx')).subarray(2, 5); +} + +function isNonZero(bytes: Uint8Array): boolean { + return bytes.some(b => b !== 0); +} + +export async function multiformatsSha256OnSubarray(): Promise { + const view = abcSlice(); + expect(view.byteOffset).to.equal(2); + const digest = await sha256.digest(view); + expect(hex(digest.digest)).to.equal(SHA256_ABC); +} + +export async function multiformatsSha512OnSubarray(): Promise { + const digest = await sha512.digest(abcSlice()); + expect(hex(digest.digest)).to.equal(SHA512_ABC); +} + +export async function hashEmptyInput(): Promise { + expect(createHash('sha256').digest('hex')).to.equal(SHA256_EMPTY); +} + +export async function hashIncrementalEqualsOneShot(): Promise { + const incremental = createHash('sha256') + .update('a') + .update(new Uint8Array([0x62])) + .update('c') + .digest('hex'); + expect(incremental).to.equal(SHA256_ABC); + expect(createHash('sha256').update('abc').digest('hex')).to.equal( + incremental, + ); +} + +export async function hashRejectsReuseAfterDigest(): Promise { + const hash = createHash('sha256').update('abc'); + hash.digest(); + expect(() => hash.update('x')).to.throw(); + expect(() => hash.digest()).to.throw(); +} + +// NIST/McGrew-Viega GCM test case 16 (AES-256, 96-bit IV, AAD). +const GCM_KEY = + 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308'; +const GCM_IV = 'cafebabefacedbaddecaf888'; +const GCM_AAD = 'feedfacedeadbeeffeedfacedeadbeefabaddad2'; +const GCM_PT = + 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' + + '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39'; +const GCM_CT = + '522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' + + '8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662'; +const GCM_TAG = '76fc6ece0f4e1768cddf8853bb2d551b'; + +function gcmDecrypt(tagHex: string): Buffer { + const decipher = createDecipheriv( + 'aes-256-gcm', + Buffer.from(GCM_KEY, 'hex'), + Buffer.from(GCM_IV, 'hex'), + ); + decipher.setAAD(Buffer.from(GCM_AAD, 'hex')); + decipher.setAuthTag(Buffer.from(tagHex, 'hex')); + return Buffer.concat([ + decipher.update(Buffer.from(GCM_CT, 'hex')), + decipher.final(), + ]); +} + +export async function aes256GcmEncryptMatchesVector(): Promise { + const cipher = createCipheriv( + 'aes-256-gcm', + Buffer.from(GCM_KEY, 'hex'), + Buffer.from(GCM_IV, 'hex'), + ); + cipher.setAAD(Buffer.from(GCM_AAD, 'hex')); + const ct = Buffer.concat([ + cipher.update(Buffer.from(GCM_PT, 'hex')), + cipher.final(), + ]); + expect(ct.toString('hex')).to.equal(GCM_CT); + expect(cipher.getAuthTag().toString('hex')).to.equal(GCM_TAG); +} + +export async function aes256GcmDecryptRoundTrip(): Promise { + expect(gcmDecrypt(GCM_TAG).toString('hex')).to.equal(GCM_PT); +} + +export async function aes256GcmRejectsTamperedTag(): Promise { + const bad = (GCM_TAG[0] === '0' ? '1' : '0') + GCM_TAG.slice(1); + expect(() => gcmDecrypt(bad)).to.throw(); +} + +// RFC 8032 section 7.1, TEST 1 (empty message). +const ED_SEED = + '9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60'; +const ED_PUB = + 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a'; +const ED_SIG = + 'e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b'; + +function pem(label: string, headerHex: string, bodyHex: string): string { + const der = Buffer.from(headerHex + bodyHex, 'hex').toString('base64'); + return `-----BEGIN ${label}-----\n${der}\n-----END ${label}-----\n`; +} + +const edPrivate = (): string => + pem('PRIVATE KEY', '302e020100300506032b657004220420', ED_SEED); +const edPublic = (): string => + pem('PUBLIC KEY', '302a300506032b6570032100', ED_PUB); + +export async function ed25519MatchesRfc8032Vector(): Promise { + const message = new Uint8Array(0); + const signature = sign(null, message, edPrivate()); + expect(signature.toString('hex')).to.equal(ED_SIG); + expect(verify(null, message, edPublic(), signature)).to.equal(true); +} + +export async function ed25519RejectsTamperedSignature(): Promise { + const signature = Buffer.from(ED_SIG, 'hex'); + signature[0] = (signature[0] ?? 0) ^ 0x01; + expect(verify(null, new Uint8Array(0), edPublic(), signature)).to.equal( + false, + ); +} + +export async function p256SignVerify(): Promise { + const { publicKey, privateKey } = generateKeyPairSync('ec', { + namedCurve: 'P-256', + }); + const message = Buffer.from('bare host p256'); + const signature = createSign('SHA256').update(message).sign(privateKey); + expect( + createVerify('SHA256').update(message).verify(publicKey, signature), + ).to.equal(true); + const tampered = Buffer.from('bare host p257'); + expect( + createVerify('SHA256').update(tampered).verify(publicKey, signature), + ).to.equal(false); +} + +export async function randomBytesSync(): Promise { + const bytes = randomBytes(32); + expect(bytes.length).to.equal(32); + expect(isNonZero(bytes)).to.equal(true); +} + +export async function randomBytesCallback(): Promise { + const bytes = await new Promise((resolve, reject) => { + randomBytes(32, (err, buf) => { + if (err || buf === undefined) reject(err ?? new Error('no bytes')); + else resolve(buf); + }); + }); + expect(bytes.length).to.equal(32); + expect(isNonZero(bytes)).to.equal(true); +} + +export async function randomFillSyncFillsView(): Promise { + const target = new Uint8Array(32); + randomFillSync(target); + expect(isNonZero(target)).to.equal(true); +} + +export async function getRandomValuesFillsView(): Promise { + const target = new Uint32Array(8); + const result = getRandomValues(target); + expect(result).to.equal(target); + expect(isNonZero(new Uint8Array(target.buffer))).to.equal(true); +} diff --git a/packages/react-native-quick-crypto/src/index.ts b/packages/react-native-quick-crypto/src/index.ts index fa26b199..369a7abf 100644 --- a/packages/react-native-quick-crypto/src/index.ts +++ b/packages/react-native-quick-crypto/src/index.ts @@ -24,6 +24,7 @@ import { constants } from './constants'; // utils import import * as utils from './utils'; +import { KeyObjectHandle } from './specs/keyObjectHandle.nitro'; import * as subtle from './subtle'; /** @@ -53,30 +54,29 @@ const QuickCrypto = { getCurves, constants, Buffer, + NativeKeyObjectHandle: KeyObjectHandle, + install, }; /** - * Optional. Patch global.crypto with react-native-quick-crypto and - * global.Buffer with react-native-buffer. + * Optional. Patch globalThis.crypto with react-native-quick-crypto and + * globalThis.Buffer with react-native-buffer. */ -export const install = () => { +export function install(): void { // @ts-expect-error copyBytesFrom and poolSizets are missing from react-native-buffer - global.Buffer = Buffer; + globalThis.Buffer = Buffer; // @ts-expect-error subtle isn't fully implemented and Cryptokey is missing - global.crypto = QuickCrypto; -}; - -// random, cipher, hash use nextTick -if (global.process == null) { - // @ts-expect-error - process is not defined - global.process = {}; -} -if (global.process.nextTick == null) { - global.process.nextTick = setImmediate; + globalThis.crypto = QuickCrypto; } -import { KeyObjectHandle } from './specs/keyObjectHandle.nitro'; +// random, cipher, hash use nextTick; bare hosts may have no process or setImmediate +const nodeProcess = (globalThis.process ??= {} as NodeJS.Process); +nodeProcess.nextTick ??= (callback, ...args): void => { + const run = (): void => callback(...args); + if (typeof setImmediate === 'function') setImmediate(run); + else Promise.resolve().then(run); +}; // exports export default QuickCrypto; @@ -105,9 +105,4 @@ export { subtle, isCryptoKeyPair } from './subtle'; export { constants } from './constants'; export { Buffer } from '@craftzdog/react-native-buffer'; -// Additional exports for CommonJS compatibility -module.exports = QuickCrypto; -module.exports.default = QuickCrypto; -module.exports.install = install; -module.exports.NativeKeyObjectHandle = KeyObjectHandle; export { KeyObjectHandle as NativeKeyObjectHandle }; diff --git a/plans/done/1104-e2e-bare-host-qualification.md b/plans/done/1104-e2e-bare-host-qualification.md new file mode 100644 index 00000000..38430db1 --- /dev/null +++ b/plans/done/1104-e2e-bare-host-qualification.md @@ -0,0 +1,60 @@ +# E2E qualification for Nitro Modules v1: RN app plus a bare-host smoke test + +Issue #1104. Run the full RN example-app E2E suite on iOS and Android for the Nitro Modules v1 port on `next`, fix failures, and add a bare-host (Hermes, no React Native) smoke test covering hash, cipher, sign/verify and random, starting from the `multiformats` SHA-2 scenario in #1099. Branch is off `next`; the PR targets `next` (squash-merge). + +Done when the full suite passes on both platforms and the bare-host check passes on Android and iOS, with evidence recorded per `docs/local-e2e.md`. + +## Live tracker + +- [x] Phase 1: Shared JS entry works under a plain bundler (`src/index.ts` ESM/CJS mix, `setImmediate` guard); bare smoke-test source (hash incl. `multiformats@13.4.2` SHA-2, AES-256-GCM, Ed25519/P-256 sign/verify, random) plus bundling config; bundle builds with no `react-native` module. +- [x] Phase 2: Bare host driver script + iOS simulator run (Nitro standalone test runner, cloned at the pinned SHA into an ignored dir, RNQC overlay). `scripts/bare-host.sh ios`; Android mode is a stub for Phase 3. +- [x] Phase 3: Android bare host (Gradle module overlay, emulator `connectedDebugAndroidTest`). `scripts/bare-host.sh android`. +- [x] Phase 4: RN qualification: `bun run e2e:ios`, then `bun run e2e:android`; fix failures. +- [x] Phase 5: Docs (`bare-host.mdx` callout and recipe). +- [x] Independent review and fixes. +- [x] Move plan, push, open PR into `next`. Attestation and screenshot publication not applicable (verifier covers PRs into `main` only). + +## Decisions + +- Bare host: Nitro's `tests/standalone` test runner with a repo-owned overlay driver script. (User, 2026-11-28.) +- Nitro checkout: the driver clones margelo/nitro at the SHA matching the pinned nightly (`43e09c161`) into an ignored build directory. (User, 2026-11-28.) +- JS entry: fix the shared `src/index.ts` so a plain bundler works; the harness keeps only the base64 alias and a minimal prelude. #1099 has nothing to borrow here (separate hash-only package; its multiformats scenario is prose only). (User, 2026-11-28.) + +## Assumptions + +- Attestation (`agentscm/local-validation`) covers PRs into `main` only (`.github/workflows/local-validation.yml`, as recorded in #1103); "evidence per `docs/local-e2e.md`" here means the artifact contract (SHA, command, result, platform, run directory) recorded in this plan and the PR. +- RN E2E runs once, after the `src/` change, rather than a baseline before it. + +- Bare smoke test lives in `example/test/bare/` (the example already pins chai and the e2e runner lives under `example/test/`; the package `test/` dir is picked up by Jest). `bundle.mjs` is plain JS because the example `tsc` has no Bun types. Output lands in the ignored `example/test/bare/build/bare-tests.js`; it bundles RNQC from `src/` (aliasing `react-native-quick-crypto`, `crypto`, `node:crypto` to `src/index.ts`) so `#nitro/*` resolves. +- `multiformats/hashes/sha2` is aliased to its Node build (`sha2.js`): the `browser` condition would otherwise pick `sha2-browser.js`, which calls `crypto.subtle.digest` and would not exercise `createHash`. +- The prelude stubs `global` and `self` (plus the Phase 2 additions below). The `Event`/`EventTarget` stubs and the example-side `bare:bundle`/`bundle.mjs` (chai 6 path) were removed after review; the driver bundles with Nitro's `bundle.ts`. +- `src/index.ts` no longer assigns `module.exports`; `install` and `NativeKeyObjectHandle` now live on the default `QuickCrypto` object, so `default.install` and named exports behave as before. +- Bare host (Phase 2): `scripts/bare-host.sh ios` fetches margelo/nitro at `43e09c161101c115720a1467a24e2d778131bfb8` (hardcoded; must move with the Nitro peer pin) into the ignored `build/bare-host/nitro`, inits only the Hermes submodule, applies `example/test/bare/host/rnqc-overlay.patch` (root `Package.swift`, `TestRuntime.cpp` `std::call_once` + `registerHybridClasses()`, iOS `build.mjs` header flags, `bundle.ts` plugin hook), rsyncs the package's shipped native files in as a local Swift package, copies the smoke test plus prelude into the runner's `js/`, and bundles with the shared `example/test/bare/aliases.mjs` plugin. The runner's chai is 5.3.3. +- The prelude also gained `console`, `AbortController`/`AbortSignal` and `kCustomPromisifiedSymbol` stubs (bare Hermes lacks them; the bundled stream polyfills and Bun's `util` polyfill read them at load). The bundle is post-processed with `@babel/plugin-transform-async-generator-functions` (added to the example as an exact-pinned dev dependency, 7.29.0, the version bun.lock already resolved) because Hermes rejects async generators and `for await`. +- iOS bare host is arm64 simulator only (the overlay's Hermes header path is the `ios-arm64-simulator` slice). `BARE_HOST_HERMES_SEED` only skips the cold Hermes build (only its `NitroTestHermes.xcframework` is copied; its path-bound `host/` CMake cache is not). +- Bare host (Phase 3): `scripts/bare-host.sh android` rsyncs the package's `android/{CMakeLists.txt,cmake,src}` into the Nitro clone's `tests/standalone/quick-crypto/android` and copies `example/test/bare/host/android/{build.gradle,host-hermes.cmake}` over it (the package's own `build.gradle` needs React Native). The overlay patch registers `:quick-crypto` in the runner's `settings.gradle`/`build.gradle` and makes `NativeTestRuntime.kt` `System.loadLibrary("QuickCrypto")` after Nitro core (the Kotlin OnLoad is `internal`); that load runs `JNI_OnLoad` -> `registerAllNatives()`, which fills the process-wide `HybridClassRegistry`, so the iOS `registerHybridClasses()` call in `TestRuntime.cpp` is now `#ifndef __ANDROID__`. The module links `nitro-core` via `api project(':nitro-core')`, `openssl-static:3.6.2-3`, and Hermes via `CMAKE_PROJECT_INCLUDE=host-hermes.cmake` (needed because the `nitro-core` Prefab adapter pulls Hermes' jsi). NDK is Nitro's `29.0.14206865` (RNQC's example uses 28.2.13676358); CMake 3.22.1, SDK 36, minSdk 26, arm64-v8a only, Debug. The script uses the device named by ANDROID_SERIAL only; otherwise it boots the first arm64-v8a AVD (or `BARE_HOST_AVD`) on port 5584 and kills it on exit. + +- Review dispositions: fixes 1-8 applied (seed copies only the XCFramework; Android result file always written; no implicit attached device; NITRO_SHA guarded against the nitro-core peer pin; shellcheck clean; `bundle.mjs`/`bare:bundle`/Event stubs removed; `aliases.mjs` uses `import.meta.resolve`; script header corrected). Skipped: Android silently accepts iOS-only flags (harmless); stale source map after the Hermes transform (debug-only); CJS `require()` of the shared entry returns a namespace with read-only getters (accepted for 2.0, documented in `bare-host.mdx`; no 2.0 migration/changelog page exists, `migration.mdx` covers other libraries). + +## Evidence + +- Phase 1, commit fcf8c298 (macOS): `bun tsc` pass; `bun lint` pass; `bun format` pass; `cd packages/react-native-quick-crypto && bun run test` 3 suites / 19 tests pass; pre-commit hooks (lint-staged, clang-format, tsc, bob build) pass. +- Phase 1, `cd example && bun run bare:bundle` builds `test/bare/build/bare-tests.js`; `node --check` parses it; no `react-native` package module in the bundle (only `react-native-quick-crypto`/`-buffer`/`-nitro` strings). Evaluating it in a bare Node `vm` context gets through all module-load globals and stops at the expected missing native `NitroModulesProxy`/utils; the tests themselves have not run (native only). Test vectors (GCM case 16, RFC 8032 test 1, SHA-2 "abc") were cross-checked against Node's crypto. + +- Phase 2, code commit d779f3a0 (macOS arm64, Xcode 27.2, bun 1.4.2 although Nitro pins 1.3.14): `scripts/bare-host.sh ios` (warm, Hermes XCFramework seeded) on the iPhone Duo simulator, iOS 27.2, arm64, exit 0: `BARE_HOST_RESULT PASS`, "Swift tests: 26 passed, 0 failed, 0 skipped" (14 runner contract tests plus the 12 Nitro JS suites and `[PASS] quick-crypto.test.ts`), no `duplicate symbol` in the build log. Cases run and passed (all 15 in the runner manifest): hashEmptyInput, hashIncrementalEqualsOneShot, hashRejectsReuseAfterDigest, multiformatsSha256OnSubarray, multiformatsSha512OnSubarray, aes256GcmEncryptMatchesVector, aes256GcmDecryptRoundTrip, aes256GcmRejectsTamperedTag, ed25519MatchesRfc8032Vector, ed25519RejectsTamperedSignature, p256SignVerify, randomBytesSync, randomBytesCallback, randomFillSyncFillsView, getRandomValuesFillsView. Result file `build/bare-host/result-ios.txt`. +- Phase 2 cold path: the same script with an empty `BARE_HOST_DIR` and no seed (fresh clone, Hermes built from source) passed identically, 8m09s, at the Phase 2 working tree equal to d779f3a0's content. +- Phase 2 negative check: corrupting the empty-input SHA-256 vector made the run exit 1 with `quick-crypto.hashEmptyInput: AssertionError ...` and `BARE_HOST_RESULT FAIL`. +- Phase 2: `shellcheck scripts/bare-host.sh`, `bun tsc`, `bun lint`, `bun format` pass; pre-commit hooks pass. No `src/` or C++ change, so the package Jest suite was not run. + +- Phase 3, code commit 4175968f (macOS arm64, NDK 29.0.14206865, CMake 3.22.1, Gradle 8.13, JDK 17): `scripts/bare-host.sh android` on AVD Nexus_7 (arm64-v8a, Android API 35, headless, emulator-5584), exit 0, cold Hermes build (about 7 min of Gradle after a full CMake build of hermesc): `BARE_HOST_RESULT PASS`, JUnit 24 tests, 0 failures, 0 errors (12 `runJavaScriptSuite[...]` Nitro suites including `[quick-crypto]`, plus 12 runner tests); all 15 quick-crypto cases in the manifest ran. Result file `build/bare-host/result-android.txt`. First runtime load of the bare Android library; no fixes to RNQC shared code were needed. Emulator was started and shut down by the script. +- Phase 3 symbol check: `llvm-nm -D --defined-only libQuickCrypto.so | grep -cE ' (EVP_|ERR_|SSL_)'` = 0 on the built arm64-v8a `.so` (the script runs it and fails the result otherwise). +- Phase 3 negative check: corrupting the empty-input SHA-256 vector made the run exit 1 with `quick-crypto.hashEmptyInput: AssertionError` and `BARE_HOST_RESULT FAIL` (1 JUnit failure); reverted and rerun PASS. +- Phase 3 iOS regression (overlay patch `TestRuntime.cpp` hunk changed): `scripts/bare-host.sh ios` rerun on the iPhone Duo simulator, exit 0, `BARE_HOST_RESULT PASS`, 26 Swift tests passed, `[PASS] quick-crypto.test.ts`. +- Phase 3: `shellcheck scripts/bare-host.sh` pass. No `src/`, `cpp/` or `android/` package change, so no Jest run and no Phase 4 dependency from this phase. + +- Phase 4, commit 0485102b (macOS): `bun run e2e:ios` passed (42 suites, 2211 tests, 0 failures; iOS simulator), run dir `example/build/e2e/ios/2026-11-29T05-08-23-149Z-51909`, result.json sha256 `a8a15d2f836c6810df61fa30b3dc700e7dca54b4f24d2347473cff7595e2db09`, screenshot sha256 `6f0b858494bc8b038d7ab857761c2124b8cbd13f56ef153ff1d0cc235c63bc54`. Then `bun run e2e:android` passed (42 suites, 2211 tests, 0 failures; Android emulator), run dir `example/build/e2e/android/2026-11-29T05-10-33-124Z-64574`, result.json sha256 `cd602e23d197f9afb7880a7f23bfea81fce88ba7e0f9b8ace37eb1c2a6742986`, screenshot sha256 `71c6f6bb02087e273d389d1da04bad05cd98a5c9f4a5b87c315c7459db642017`. No fixes were needed. Evidence stays current: later commits touch neither `packages/` nor the example app's runtime code. +- Review fixes, commit b1ea9420 (macOS arm64; runs made on the uncommitted working tree that became b1ea9420, result files record rnqc 0485102b): `scripts/bare-host.sh ios` exit 0, `BARE_HOST_RESULT PASS`, 26 Swift tests passed, `[PASS] quick-crypto.test.ts`, 15 cases. `scripts/bare-host.sh android` (no ANDROID_SERIAL, own AVD Nexus_7 on emulator-5584, shut down afterwards) exit 0, `BARE_HOST_RESULT PASS`, JUnit 24 tests 0 failures 0 errors, 0 exported EVP_/ERR_/SSL_ symbols. Negative simulation of `finish_android` with no built `.so`/JUnit output: exit 1, `BARE_HOST_RESULT FAIL` file written. `shellcheck scripts/bare-host.sh`, `bun tsc`, `bun lint`, `bun format` pass; pre-commit hooks pass. `import.meta.resolve('multiformats/hashes/sha2')` under Bun resolves to `dist/src/hashes/sha2.js` (Node build); the bare run's multiformats cases pass. + +## Unverified + +- The bare iOS run is arm64 simulator only, Debug, and on bun 1.4.2 rather than Nitro's pinned 1.3.14. The bare Android run is a single API 35 arm64-v8a emulator (Nexus_7 tablet AVD), Debug, NDK 29 (Nitro's) rather than RNQC's 28.2; no x86_64, no Release, no physical device. Android per-suite JUnit durations are not meaningful (runner reports wait time). diff --git a/scripts/bare-host.sh b/scripts/bare-host.sh new file mode 100755 index 00000000..ef0934c6 --- /dev/null +++ b/scripts/bare-host.sh @@ -0,0 +1,278 @@ +#!/usr/bin/env bash +# +# Bare-host smoke test: runs RNQC's shared JS entry and native sources inside +# Nitro Modules' standalone test runner (Hermes, no React Native). +# +# Usage: +# scripts/bare-host.sh ios [--os VERSION] [--device NAME] [--skip-build] +# scripts/bare-host.sh android [--skip-build] +# +# It clones margelo/nitro at the pinned NITRO_SHA (below) into build/bare-host/nitro +# (ignored), applies the overlay in example/test/bare/host, copies the package's +# shipped native files in as a local Swift package, bundles example/test/bare +# into the runner's JS, then builds and runs the runner on an iOS simulator. +# The result lands in build/bare-host/result-ios.txt; exits non-zero on failure. +# +# `android` builds the runner's instrumented JUnit library with QuickCrypto linked +# in (Gradle module overlay, Hermes built from source on first run) and runs +# connectedDebugAndroidTest on an arm64-v8a emulator or device. It uses the device +# named by ANDROID_SERIAL; otherwise it boots its own BARE_HOST_AVD (first +# arm64-v8a AVD when unset) on port 5584 and shuts it down afterwards. Other +# attached devices are never used implicitly. +# Result: build/bare-host/result-android.txt. +# +# Prerequisites: Xcode (iphonesimulator SDK and a simulator runtime), bun, cmake, +# ninja, git, rsync, a bun-installed repo (example/node_modules provides the +# base64-js and multiformats packages that aliases.mjs resolves), and network +# access on first run +# (Nitro, Hermes, OpenSSL binary target, simdutf-swift). +# +# Environment: +# BARE_HOST_DIR work directory (default: /build/bare-host) +# BARE_HOST_HERMES_SEED optional path to a prebuilt tests/standalone/.build/hermes +# from the same Nitro SHA, copied in to skip the cold Hermes build +# BARE_HOST_IOS_OS simulator OS version (default: newest installed iOS) +# BARE_HOST_AVD Android: AVD name to boot (when ANDROID_SERIAL is unset) + +set -euo pipefail + +# Must move with the Nitro Modules peer pin (1.0.0-alpha.nightly.138.g43e09c161101). +NITRO_SHA=43e09c161101c115720a1467a24e2d778131bfb8 + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +pkg="$repo_root/packages/react-native-quick-crypto" +overlay="$repo_root/example/test/bare/host" +bare_tests="$repo_root/example/test/bare" +work="${BARE_HOST_DIR:-$repo_root/build/bare-host}" +nitro="$work/nitro" + +die() { echo "error: $*" >&2; exit 2; } +step() { echo "==> $*"; } + +grep -q "\"nitro-core\": \"[^\"]*g${NITRO_SHA:0:12}\"" "$pkg/package.json" \ + || die "NITRO_SHA does not match the nitro-core peer pin in $pkg/package.json" + +mode="${1:-}" +[[ -n "$mode" ]] && shift +ios_os="${BARE_HOST_IOS_OS:-}" +device="" +skip_build=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --os) ios_os="${2:?--os needs a version}"; shift 2 ;; + --device) device="${2:?--device needs a name}"; shift 2 ;; + --skip-build) skip_build=1; shift ;; + -h|--help) sed -n '2,/^set /p' "$0" | sed '$d'; exit 0 ;; + *) die "unknown argument: $1" ;; + esac +done +case "$mode" in + ios) ;; + android) ;; + *) die "usage: scripts/bare-host.sh ios|android [options]" ;; +esac + +ensure_nitro() { + step "Nitro checkout at ${NITRO_SHA:0:9}" + if [[ "$(git -C "$nitro" rev-parse HEAD 2>/dev/null || true)" != "$NITRO_SHA" ]]; then + rm -rf "$nitro" + mkdir -p "$nitro" + git -C "$nitro" init -q + git -C "$nitro" remote add origin https://github.com/margelo/nitro.git + git -C "$nitro" fetch -q --depth 1 --filter=blob:none origin "$NITRO_SHA" + git -C "$nitro" checkout -q --detach FETCH_HEAD + fi + [[ "$(git -C "$nitro" rev-parse HEAD)" == "$NITRO_SHA" ]] || die "Nitro checkout is not at $NITRO_SHA" + git -C "$nitro" submodule update --init --depth 1 -- tests/standalone/hermes/hermes + (cd "$nitro" && bun install --frozen-lockfile) +} + +apply_overlay() { + step "Applying RNQC overlay" + git -C "$nitro" checkout -q -- . + git -C "$nitro" apply "$overlay/rnqc-overlay.patch" + + local pkg_dest="$nitro/tests/standalone/quick-crypto" + if [[ "$mode" == ios && ! -d "$pkg/ios/openssl/include" ]]; then (cd "$pkg" && bun run prepare:openssl-apple); fi + [[ -d "$pkg/nitrogen/generated" ]] || die "nitrogen output missing: run 'bun --filter=react-native-quick-crypto specs'" + mkdir -p "$pkg_dest" + rsync -a --delete \ + --include='/Package.swift' --include='/nitro.json' \ + --include='/apple/***' --include='/cpp/***' --include='/nitrogen/***' \ + --include='/android/' --include='/android/CMakeLists.txt' --include='/android/cmake/***' --include='/android/src/***' \ + --include='/ios/' --include='/ios/openssl/***' \ + --include='/deps/' --include='/deps/ncrypto/***' --include='/deps/simdutf/***' \ + --include='/deps/fastpbkdf2/***' --include='/deps/blake3/' --include='/deps/blake3/c/***' \ + --exclude='*' "$pkg/" "$pkg_dest/" + # The package's own build.gradle needs React Native; the bare host links against nitro-core. + cp "$overlay/android/build.gradle" "$overlay/android/host-hermes.cmake" "$pkg_dest/android/" + + # The runner discovers js/**/*.test.ts; the prelude must evaluate first. + local js="$nitro/tests/standalone/test-runner/js" + cp "$bare_tests/prelude.ts" "$js/rnqc-prelude.ts" + { echo "import './rnqc-prelude'"; cat "$bare_tests/quick-crypto.test.ts"; } > "$js/quick-crypto.test.ts" +} + +bundle_js() { + step "Bundling JS" + (cd "$nitro/tests/standalone/test-runner" && RNQC_BARE_ALIASES="$bare_tests/aliases.mjs" bun scripts/bundle.ts \ + && bun "$overlay/hermes-transform.mjs" build/runtime-tests.js) +} + +seed_hermes() { + local dest="$nitro/tests/standalone/.build/hermes" + if [[ ! -d "$dest/NitroTestHermes.xcframework" && -n "${BARE_HOST_HERMES_SEED:-}" ]]; then + step "Seeding Hermes from $BARE_HOST_HERMES_SEED" + mkdir -p "$dest" + [[ -d "$BARE_HOST_HERMES_SEED/NitroTestHermes.xcframework" ]] || die "no NitroTestHermes.xcframework in $BARE_HOST_HERMES_SEED" + cp -R "$BARE_HOST_HERMES_SEED/NitroTestHermes.xcframework" "$dest/" + fi +} + +pick_ios_os() { + [[ -n "$ios_os" ]] && return + ios_os="$(xcrun simctl list runtimes available | sed -n 's/^iOS \([0-9.]*\) .*/\1/p' | sort -V | tail -1)" + [[ -n "$ios_os" ]] || die "no iOS simulator runtime installed" +} + +build_ios() { + step "Building (Hermes is built cold when no XCFramework exists)" + local args=(--arch arm64) + [[ -d "$nitro/tests/standalone/.build/hermes/NitroTestHermes.xcframework" ]] && args+=(--skip-hermes-build) + (cd "$nitro" && bun tests/standalone/test-runner/ios/build.mjs "${args[@]}") 2>&1 | tee "$work/ios-build.log" + [[ ${PIPESTATUS[0]} -eq 0 ]] || return 1 + if grep -q 'duplicate symbol' "$work/ios-build.log"; then + echo "build log contains duplicate symbols" >&2 + return 1 + fi +} + +run_ios() { + step "Running on iOS $ios_os simulator" + local args=(--arch arm64 --os "$ios_os") + [[ -n "$device" ]] && args+=(--device "$device") + (cd "$nitro" && bun tests/standalone/test-runner/ios/run.mjs "${args[@]}") 2>&1 | tee "$work/ios-run.log" + return "${PIPESTATUS[0]}" +} + +android_home() { echo "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}"; } + +emulator_pid="" +# shellcheck disable=SC2329 # invoked via trap +stop_emulator() { + [[ -n "$emulator_pid" ]] || return 0 + adb -s "$android_serial" emu kill >/dev/null 2>&1 || kill "$emulator_pid" 2>/dev/null || true + wait "$emulator_pid" 2>/dev/null || true +} + +ensure_device() { + local sdk; sdk="$(android_home)" + export ANDROID_HOME="$sdk" + export PATH="$sdk/platform-tools:$sdk/emulator:$PATH" + android_serial="${ANDROID_SERIAL:-}" + if [[ -z "$android_serial" ]]; then + local avd="${BARE_HOST_AVD:-}" + if [[ -z "$avd" ]]; then + for candidate in $(emulator -list-avds); do + if grep -q '^abi.type=arm64-v8a' "$HOME/.android/avd/$candidate.avd/config.ini" 2>/dev/null; then avd="$candidate"; break; fi + done + fi + [[ -n "$avd" ]] || die "no arm64-v8a AVD found; set BARE_HOST_AVD" + step "Booting AVD $avd on emulator-5584" + emulator -avd "$avd" -port 5584 -no-window -no-snapshot -no-audio -no-boot-anim -gpu swiftshader_indirect \ + "$work/emulator.log" 2>&1 & + emulator_pid=$! + android_serial=emulator-5584 + trap stop_emulator EXIT + local waited=0 + until [[ "$(adb -s "$android_serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" == 1 ]]; do + kill -0 "$emulator_pid" 2>/dev/null || { cat "$work/emulator.log" >&2; die "emulator exited"; } + sleep 2; waited=$((waited + 2)) + [[ $waited -lt 300 ]] || die "emulator boot timed out" + done + fi + export ANDROID_SERIAL="$android_serial" + android_abi="$(adb -s "$android_serial" shell getprop ro.product.cpu.abi | tr -d '\r')" + [[ "$android_abi" == arm64-v8a ]] || die "device ABI is $android_abi; the bare host builds arm64-v8a only" + android_api="$(adb -s "$android_serial" shell getprop ro.build.version.sdk | tr -d '\r')" +} + +run_android() { + local gradle=("$nitro/tests/standalone/test-runner/android/gradlew" --no-daemon) + (cd "$nitro/tests/standalone/test-runner/android" && ANDROID_SERIAL="$android_serial" "${gradle[@]}" :connectedDebugAndroidTest) 2>&1 | tee "$work/android-run.log" + return "${PIPESTATUS[0]}" +} + +# Prints "tests failures errors skipped" summed over the JUnit result files. +android_totals() { + local dir="$nitro/tests/standalone/test-runner/android/build/outputs/androidTest-results/connected" + find "$dir" -name 'TEST-*.xml' -print0 2>/dev/null | xargs -0 cat 2>/dev/null \ + | sed -n 's/.*]*tests="\([0-9]*\)"[^>]*failures="\([0-9]*\)"[^>]*errors="\([0-9]*\)".*/\1 \2 \3/p' \ + | awk '{t+=$1; f+=$2; e+=$3} END {print t+0, f+0, e+0}' +} + +finish_android() { + local status=$1 tests failures errors verdict=FAIL + read -r tests failures errors <<<"$(android_totals)" + local so; so="$(find "$nitro/tests/standalone/quick-crypto/android/build" -path '*obj/arm64-v8a/libQuickCrypto.so' -o -path '*stripped_native_libs*arm64-v8a/libQuickCrypto.so' 2>/dev/null | head -1)" || true + local ndk_nm; ndk_nm="$(find "$(android_home)/ndk/$(sed -n 's/^nitroTestNdkVersion=//p' "$nitro/tests/standalone/test-runner/android/gradle.properties")" -name llvm-nm -path '*darwin*' 2>/dev/null | head -1)" || true + local leaked="unknown" + [[ -n "$so" && -n "$ndk_nm" ]] && leaked="$("$ndk_nm" -D --defined-only "$so" | grep -cE ' (EVP_|ERR_|SSL_)' || true)" + if [[ $status -eq 0 && ${tests:-0} -gt 0 && ${failures:-0} -eq 0 && ${errors:-0} -eq 0 && "$leaked" == 0 ]]; then verdict=PASS; else status=1; fi + { + echo "BARE_HOST_RESULT $verdict" + echo "platform: android API ${android_api:-?}, ${android_abi:-?}, $android_serial" + echo "nitro: $NITRO_SHA" + echo "rnqc: $(git -C "$repo_root" rev-parse HEAD)" + echo "JUnit: tests=${tests:-0} failures=${failures:-0} errors=${errors:-0}" + echo "libQuickCrypto.so exported EVP_/ERR_/SSL_ symbols: $leaked" + grep -E 'quick-crypto' "$work/android-run.log" 2>/dev/null | head -5 || true + echo "cases:" + (cd "$nitro/tests/standalone/test-runner" && bun -e 'console.log(require("./build/runtime-tests.json")["quick-crypto"].join("\n"))') | sed 's/^/ /' + } | tee "$work/result-android.txt" + echo "result file: $work/result-android.txt" + exit "$status" +} + +if [[ "$mode" == android ]]; then + mkdir -p "$work" + ensure_nitro + apply_overlay + bundle_js + ensure_device + status=0 + if [[ $skip_build -eq 1 ]]; then step "Gradle (--skip-build is a no-op: connectedDebugAndroidTest builds)"; fi + step "Running on $android_serial (API $android_api, $android_abi)" + run_android || status=$? + finish_android "$status" +fi + +mkdir -p "$work" +ensure_nitro +apply_overlay +bundle_js +seed_hermes +pick_ios_os + +status=0 +if [[ $skip_build -eq 0 ]]; then build_ios || status=$?; fi +[[ $status -eq 0 ]] && { run_ios || status=$?; } + +summary_line="$(grep -E '^Swift tests:' "$work/ios-run.log" 2>/dev/null | tail -1 || true)" +# The suite file's pass/fail line is the proof the bundle's smoke cases ran. +suite_pass=0 +grep -q '^\[PASS\] quick-crypto\.test\.ts' "$work/ios-run.log" 2>/dev/null && suite_pass=1 +if [[ $status -eq 0 && $suite_pass -eq 1 ]]; then verdict=PASS; else verdict=FAIL; status=1; fi +{ + echo "BARE_HOST_RESULT $verdict" + echo "platform: ios simulator, iOS $ios_os, arm64" + echo "nitro: $NITRO_SHA" + echo "rnqc: $(git -C "$repo_root" rev-parse HEAD)" + echo "${summary_line:-no Swift test summary}" + grep -E '^\[(PASS|FAIL|SKIP)\] quick-crypto' "$work/ios-run.log" 2>/dev/null || true + # The runner executes every case in the manifest and fails the suite if one fails. + echo "cases:" + (cd "$nitro/tests/standalone/test-runner" && bun -e 'console.log(require("./build/runtime-tests.json")["quick-crypto"].join("\n"))') | sed 's/^/ /' +} | tee "$work/result-ios.txt" +echo "result file: $work/result-ios.txt" +exit "$status"