@trustpin/react-native-attest 0.0.0-stage → 7.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/LICENSE +59 -0
  2. package/README.md +281 -2
  3. package/TrustPinReactNativeAttest.podspec +33 -0
  4. package/android/build.gradle +121 -0
  5. package/android/src/main/AndroidManifest.xml +1 -0
  6. package/android/src/main/kotlin/cloud/trustpin/reactnative/attest/AttestEventHub.kt +106 -0
  7. package/android/src/main/kotlin/cloud/trustpin/reactnative/attest/AttestExecution.kt +59 -0
  8. package/android/src/main/kotlin/cloud/trustpin/reactnative/attest/AttestWire.kt +139 -0
  9. package/android/src/main/kotlin/cloud/trustpin/reactnative/attest/TrustPinReactNativeAttest.kt +115 -0
  10. package/android/src/main/kotlin/cloud/trustpin/reactnative/attest/TrustPinReactNativeAttestModule.kt +119 -0
  11. package/android/src/main/kotlin/cloud/trustpin/reactnative/attest/TrustPinReactNativeAttestPackage.kt +31 -0
  12. package/app.plugin.js +4 -0
  13. package/ios/TrustPinAttestBridge.swift +198 -0
  14. package/ios/TrustPinAttestEventHub.swift +96 -0
  15. package/ios/TrustPinAttestWire.swift +203 -0
  16. package/ios/TrustPinReactNativeAttest.swift +92 -0
  17. package/ios/TrustPinReactNativeAttestModule.h +11 -0
  18. package/ios/TrustPinReactNativeAttestModule.mm +122 -0
  19. package/lib/NativeTrustPinReactNativeAttest.d.ts +59 -0
  20. package/lib/NativeTrustPinReactNativeAttest.js +4 -0
  21. package/lib/errors.d.ts +48 -0
  22. package/lib/errors.js +69 -0
  23. package/lib/index.d.ts +175 -0
  24. package/lib/index.js +262 -0
  25. package/package.json +69 -4
  26. package/plugin/build/afterDangerous.d.ts +8 -0
  27. package/plugin/build/afterDangerous.js +22 -0
  28. package/plugin/build/android.d.ts +16 -0
  29. package/plugin/build/android.js +109 -0
  30. package/plugin/build/index.d.ts +5 -0
  31. package/plugin/build/index.js +20 -0
  32. package/plugin/build/ios.d.ts +16 -0
  33. package/plugin/build/ios.js +129 -0
  34. package/plugin/build/types.d.ts +40 -0
  35. package/plugin/build/types.js +45 -0
  36. package/src/NativeTrustPinReactNativeAttest.ts +65 -0
  37. package/src/errors.ts +73 -0
  38. package/src/index.ts +351 -0
package/LICENSE ADDED
@@ -0,0 +1,59 @@
1
+ TrustPin Binary License Agreement
2
+ Version 1.0 – July 2025
3
+ https://trustpin.cloud
4
+
5
+ This license governs the use of the TrustPin SDKs, CLI tools, and associated binaries (collectively, the "Software") made available by TrustPin at trustpin.cloud and app.trustpin.cloud.
6
+
7
+ By using the Software, you agree to the following terms:
8
+
9
+ -----
10
+
11
+ 1. **Grant of Use**
12
+ You are granted a non-exclusive, non-transferable, royalty-free license to use the Software in its compiled binary form, including in commercial and enterprise environments, subject to the terms of your active TrustPin plan (including free and paid tiers).
13
+ 1. **No Modification or Reverse Engineering**
14
+ You may not modify, decompile, disassemble, reverse-engineer, or create derivative works based on the Software. The Software is provided solely for use as-is.
15
+ 1. **No Redistribution**
16
+ You may not sell, redistribute, sublicense, or publicly publish the Software, in whole or in part, without prior written permission from TrustPin.
17
+ 1. **Use with TrustPin Platform Only**
18
+ The Software must be used exclusively through the authorized TrustPin platform interfaces, which include:
19
+ (a) the official TrustPin SDKs,
20
+ (b) the official TrustPin CLI tools, and
21
+ (c) the TrustPin web applications at https://trustpin.cloud and https://app.trustpin.cloud.
22
+
23
+ You may not access TrustPin APIs directly outside of these authorized interfaces, including but not limited to web scraping, reverse-engineering API endpoints, or creating custom clients that interact with TrustPin services, without explicit written authorization.
24
+
25
+ 1. **Trademark Notice**
26
+ "TrustPin" and the TrustPin logo are trademarks of Capa7 LLC. You may not use these trademarks without express written permission, except as necessary for the proper attribution described below.
27
+ 1. **Attribution (Required)**
28
+ If you integrate the Software into your own applications, you must prominently display the following notice in your application's "About" screen, license page, or comparable documentation. The notice must be clearly visible, in a font size no smaller than 10pt (or visually equivalent):
29
+
30
+ "Uses TrustPin™ technology – https://trustpin.cloud"
31
+ 1. **Source Code Restrictions**
32
+ This license does not grant access to, or any rights over, the source code of the Software. All rights, title, and interest in and to the Software, including all associated intellectual property, remain the sole property of Capa7 LLC. This license does not grant you any ownership of the Software or the TrustPin trademark.
33
+ 1. **Competitive Use Restrictions**
34
+ You may not use the Software to build, develop, or offer any product or service that competes with TrustPin, or to bypass usage restrictions, rate limits, or other limitations defined in your TrustPin plan. This includes, but is not limited to, creating alternative interfaces, wrappers, or derivative services that replicate or replace TrustPin functionality.
35
+ 1. **Plan Termination**
36
+ If your TrustPin plan is cancelled, suspended, or expired, your license to use the Software is automatically revoked. You must cease all use and remove the Software from your systems within 30 days of termination.
37
+ 1. **No Warranty**
38
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND. Capa7 LLC DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
39
+ 1. **Limitation of Liability**
40
+ IN NO EVENT SHALL Capa7 LLC BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES ARISING OUT OF OR RELATING TO THIS LICENSE OR THE SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
41
+ 1. **Termination for Breach**
42
+ Your rights under this license terminate automatically upon any material breach of its terms. Upon termination, you must cease all use and destroy all copies of the Software in your possession or control.
43
+ 1. **Governing Law and Jurisdiction**
44
+ This license is governed by and construed in accordance with the laws of the Kingdom of Spain. Any disputes arising under or in connection with this license shall be subject to the exclusive jurisdiction of the courts of Madrid, Spain.
45
+ 1. **Entire Agreement**
46
+ This license constitutes the entire agreement between you and the author regarding use of the Software and supersedes all prior communications, proposals, or agreements.
47
+ 1. **Survival**
48
+ Sections 6 (Attribution), 10 (No Warranty), and 11 (Limitation of Liability) shall survive termination of this license.
49
+ 1. **Contact and Licensing Inquiries**
50
+ For commercial redistribution, enterprise licensing, or custom agreements, contact:
51
+ 📧 contact@trustpin.cloud
52
+ 🔗 https://trustpin.cloud
53
+
54
+ -----
55
+
56
+ Copyright (c) 2025 Capa7 LLC
57
+ TrustPin is a trademark of Capa7 LLC
58
+
59
+ This license is effective as of the date you first use the Software and remains in effect until terminated in accordance with its terms.
package/README.md CHANGED
@@ -1,3 +1,282 @@
1
- # Temporary Holding Version
1
+ # TrustPin App Attestation for React Native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@trustpin/react-native-attest.svg)](https://www.npmjs.com/package/@trustpin/react-native-attest)
4
+
5
+ Proves to your API that a request comes from **your genuine app on a genuine
6
+ device** that meets your policy. The device attests once per device key to
7
+ **your own** TrustPin verifier (Apple App Attest, Android Key Attestation or
8
+ Play Integrity), then renews a short-lived token cheaply. The token travels in
9
+ the `TrustPin-Attestation` header, and your API or gateway verifies it.
10
+
11
+ This package is a thin wrapper of the native attestation modules,
12
+ `TrustPinAttestKit` and `cloud.trustpin:kotlin-attest` 7.1.x. It is separate
13
+ from [`@trustpin/react-native`](https://www.npmjs.com/package/@trustpin/react-native),
14
+ the pinning package, which it requires: the SDK pins its calls to your
15
+ verifier, and adds the header to your app's requests.
16
+
17
+ Attestation is not runtime protection: it doesn't detect hooking, debugging,
18
+ tampering, root or jailbreak. Setup, the policy, deploying the verifier and
19
+ verifying tokens are covered at [docs.trustpin.cloud](https://docs.trustpin.cloud).
20
+
21
+ ## Requirements
22
+
23
+ | | Minimum |
24
+ |---|---|
25
+ | React Native | **0.85** (New Architecture only) |
26
+ | `@trustpin/react-native` | the same version, **7.1.x** |
27
+ | iOS | 15.0+ |
28
+ | Android | minSdk 25 (Android 7.1), **Kotlin 2.3.0** |
29
+ | Verifier | contract version 2 or newer (verifier 1.0.0 or later) |
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ npm install @trustpin/react-native @trustpin/react-native-attest
35
+ ```
36
+
37
+ Both packages must be on the same version.
38
+
39
+ ## Before you write code
40
+
41
+ - **The policy:** in the TrustPin console, list your app (Team ID and bundle
42
+ ID, or package name and signing-certificate digests) and publish the policy.
43
+ - **Your verifier:** deployed and reachable from the app, and its host
44
+ registered as a domain of your TrustPin project, because verifier calls are
45
+ pinned. In strict mode an unregistered verifier host fails every call
46
+ (`VERIFIER_UNAVAILABLE`) and no header is sent. An older verifier is refused
47
+ (`VERIFIER_INCOMPATIBLE`).
48
+ - **iOS:** the **App Attest** capability, which adds the entitlement
49
+ `com.apple.developer.devicecheck.appattest-environment`: `development` for
50
+ builds run from Xcode, `production` for TestFlight and the App Store.
51
+ - **Android with Play Integrity:** the number of the Google Cloud project
52
+ linked to the app in Play Console.
53
+
54
+ ## Setup — Expo
55
+
56
+ List this plugin with the pinning one:
57
+
58
+ ```json
59
+ {
60
+ "expo": {
61
+ "plugins": [
62
+ ["@trustpin/react-native", { "organizationId": "…", "projectId": "…", "publicKey": "…" }],
63
+ ["@trustpin/react-native-attest", {
64
+ "verifierUrl": "https://attest.example.com",
65
+ "attestedHosts": ["api.example.com"],
66
+ "appAttestEnvironment": "development"
67
+ }]
68
+ ]
69
+ }
70
+ }
71
+ ```
72
+
73
+ `npx expo prebuild` adds the attestation keys to the configuration files the
74
+ pinning plugin writes, adds the App Attest entitlement, and starts attestation
75
+ right after pinning on both platforms. Expo Go cannot run it: use a
76
+ development build.
77
+
78
+ | Prop | Type | Notes |
79
+ |------|------|-------|
80
+ | `verifierUrl` | string | Your verifier, `https://` on a host name, without credentials, query or fragment. Set it with `attestedHosts`, or neither when your pinning `configFile`s already carry the keys. |
81
+ | `attestedHosts` | string[] | The hosts that receive the header: exact names, or `*.example.com` for exactly one label. No other host ever receives it. |
82
+ | `googleCloudProjectNumber` | string | Android, when the policy uses Play Integrity. |
83
+ | `appAttestEnvironment` | `development` \| `production` | The iOS entitlement's value. Defaults to `production`. |
84
+ | `logLevel` | `none` \| `error` \| `warning` \| `info` \| `debug` | Passed to the native init helper. |
85
+
86
+ ## Setup — bare React Native
87
+
88
+ ### 1. Add the attestation keys
89
+
90
+ To the files the pinning setup reads.
91
+
92
+ **iOS**, `TrustPin-Info.plist`:
93
+
94
+ ```xml
95
+ <key>AttestVerifierURL</key>
96
+ <string>https://attest.example.com</string>
97
+ <key>AttestedHosts</key>
98
+ <array>
99
+ <string>api.example.com</string>
100
+ </array>
101
+ ```
102
+
103
+ **Android**, `assets/trustpin.json`:
104
+
105
+ ```json
106
+ "attest_verifier_url": "https://attest.example.com",
107
+ "attested_hosts": ["api.example.com"],
108
+ "google_cloud_project_number": "123456789012"
109
+ ```
110
+
111
+ Leave `google_cloud_project_number` out unless the policy uses Play
112
+ Integrity: with a number, the app contacts Google Play services from setup on.
113
+
114
+ ### 2. Start attestation after pinning
115
+
116
+ **iOS**, `AppDelegate.swift`:
117
+
118
+ ```swift
119
+ import TrustPinReactNative
120
+ import TrustPinReactNativeAttest
121
+
122
+ TrustPinReactNative.start()
123
+ TrustPinReactNativeAttest.start() // or: .start(logLevel: .debug)
124
+ ```
125
+
126
+ **Android**, `MainApplication.kt`:
127
+
128
+ ```kotlin
129
+ import cloud.trustpin.reactnative.TrustPinReactNative
130
+ import cloud.trustpin.reactnative.attest.TrustPinReactNativeAttest
131
+
132
+ override fun onCreate() {
133
+ TrustPinReactNative.start(this)
134
+ TrustPinReactNativeAttest.start(this) // or: .start(this, TrustPinAttestLogLevel.DEBUG)
135
+ super.onCreate()
136
+ loadReactNative(this)
137
+ }
138
+ ```
139
+
140
+ Then `cd ios && pod install`, and rebuild. Setup makes no verifier call: it
141
+ validates the configuration and loads a device key from an earlier launch. A
142
+ failure never crashes the app; it shows in the log and the state, and requests
143
+ go out without the header.
144
+
145
+ ## Send the header
146
+
147
+ **Nothing to change.** React Native's networking (`fetch`,
148
+ `XMLHttpRequest`, axios) carries the header to the attested hosts, added
149
+ natively:
150
+
151
+ - Requests are never failed by the SDK: when no token is ready in a short,
152
+ bounded time, the request goes out **without** the header, and your API
153
+ decides.
154
+ - A header the request already carries is kept.
155
+ - A redirect never carries the header to another host: each redirect gets the
156
+ header for its own URL only.
157
+
158
+ For transports React Native's networking doesn't carry (gRPC, some WebSocket
159
+ clients), send `await TrustPinAttest.getToken()` in the `TrustPin-Attestation`
160
+ header. For other HTTP clients, `TrustPinAttest.attestationHeaders(url, { headers })`
161
+ returns the headers to add.
162
+
163
+ ## Bind tokens to the user's session
164
+
165
+ ```ts
166
+ import TrustPinAttest from '@trustpin/react-native-attest';
167
+
168
+ await TrustPinAttest.bindToHeader('Authorization');
169
+ TrustPinAttest.prefetch();
170
+ ```
171
+
172
+ Each token is then bound to the request's `Authorization` value: only its
173
+ SHA-256 travels, and a token taken from one session is useless with another.
174
+ `setTokenBinding(value)` binds to a fixed value instead. A new binding renews
175
+ the token with the same device key.
176
+
177
+ ## Sensitive operations: assertions
178
+
179
+ For an operation that must come from this device, such as a payment, send an
180
+ assertion next to the token. It binds the device's attested key to a SHA-256
181
+ digest of your choice, typically the request body:
182
+
183
+ ```ts
184
+ const body = JSON.stringify({ amount: '1.00', to: 'demo' });
185
+ const headers = { Authorization: `Bearer ${session}`, 'Content-Type': 'application/json' };
186
+ Object.assign(headers, await TrustPinAttest.assertionHeaders(sha256(body))); // 32 bytes
187
+ await fetch(url, { method: 'POST', headers, body });
188
+ ```
189
+
190
+ - `assertionHeaders` takes the digest as 32 bytes (`Uint8Array` or
191
+ `ArrayBuffer`) or 64 hex characters, and returns both headers: the token and
192
+ `TrustPin-Assertion`. Each call produces a new assertion: one per operation.
193
+ - Your backend passes both headers and its own digest of what it received to
194
+ your verifier.
195
+ - It rejects with `INVALID_DIGEST` for a digest that isn't 32 bytes, and with
196
+ the usual codes when no token is available.
197
+
198
+ React Native has no built-in digest API; use your crypto library of choice.
199
+
200
+ ## Simulators, emulators and debug tokens
201
+
202
+ Simulators and emulators can't produce real evidence. Pass a debug token from
203
+ the build, never from a file:
204
+
205
+ - **iOS simulator:** set `TRUSTPIN_DEBUG_TOKEN` in the Xcode scheme's
206
+ environment, or pass `TrustPinReactNativeAttest.start(debugToken:)` from a
207
+ debug-only build setting. Ignored on devices.
208
+ - **Android:** pass `TrustPinReactNativeAttest.start(this, level, debugToken)`
209
+ from a debug-only `BuildConfig` field. Used only in debuggable builds.
210
+
211
+ Your policy (**Allow debug tokens**) and your verifier must both allow debug
212
+ tokens. Their tokens carry `tp.env` `debug`, which production APIs refuse.
213
+
214
+ ## State, events, errors and logging
215
+
216
+ ```ts
217
+ const subscription = TrustPinAttest.onStateChange(state => {
218
+ switch (state.status) {
219
+ case 'unavailable': return console.log('No token yet');
220
+ case 'attesting': return console.log('Attesting…');
221
+ case 'ready': return console.log('Token ready until', new Date(state.expiresAtMs));
222
+ case 'failed': return console.log('Failed:', state.error.code, state.retryAtMs ?? 'after restart');
223
+ }
224
+ });
225
+ ```
226
+
227
+ - `onStateChange` delivers the current state first, then every change.
228
+ - After a failure no timer runs: nothing is tried before `retryAtMs`, and the
229
+ next request, `getToken()` or `prefetch()` after it starts a new attempt. A
230
+ `null` `retryAtMs` means no new attempt in this launch, until `reset()` or a
231
+ restart, except `BINDING_REQUIRED`, which resumes once a binding is set.
232
+ - `onEvent` reports what the SDK did, for your monitoring: keys generated or
233
+ replaced, attestations and renewals with their durations, refusals and waits
234
+ with their end, unsupported devices, an unreachable verifier, and
235
+ assertions. Events never contain a token, a key or a device identifier, and
236
+ those from before JavaScript was running replay to the first subscriber.
237
+ New event types can appear in a minor release: keep a default case.
238
+ - Errors are `TrustPinAttestError` with a stable `code`:
239
+
240
+ | Code | Meaning |
241
+ |---|---|
242
+ | `INVALID_CONFIGURATION` | A configuration value was rejected, or the file is missing |
243
+ | `ALREADY_INITIALIZED` | Setup ran twice |
244
+ | `NOT_SET_UP` | The native init helper never ran |
245
+ | `UNSUPPORTED_DEVICE` | App Attest is unsupported on this device (iOS) |
246
+ | `EVIDENCE_UNAVAILABLE` | The device can't produce the evidence the policy requires |
247
+ | `BINDING_REQUIRED` | The policy requires a binding and none is set yet |
248
+ | `ATTESTATION_FAILED` | The verifier refused; see `reasons` |
249
+ | `VERIFIER_UNAVAILABLE` | The verifier couldn't be reached, including when strict pinning refuses its host |
250
+ | `VERIFIER_INCOMPATIBLE` | The verifier is too old for this SDK; update it |
251
+ | `INVALID_DIGEST` | `assertionHeaders` got a digest that isn't 32 bytes |
252
+
253
+ New codes can appear in a minor release: handle unknown ones.
254
+
255
+ - Logging is off by default: `setLogLevel('debug')` in development, and
256
+ `onLogEvent` to route messages. Logs never contain tokens, key
257
+ certificates, bound values or debug tokens.
258
+ - `reset()` discards the device key, so the token's `sub` changes. It's for
259
+ support flows, not routine use, and does nothing before setup.
260
+
261
+ ## Backups and privacy
262
+
263
+ - Device keys and key certificates are never backed up or synced: a restored
264
+ app attests again.
265
+ - Evidence and tokens go only to your verifier, nothing to TrustPin.
266
+ - iOS: the native framework ships a privacy manifest (no tracking, no
267
+ collected data).
268
+ - Android: with a Google Cloud project number configured, the app uses the
269
+ Play Integrity API; declare it in Play Console's Data safety form.
270
+
271
+ ## Example apps
272
+
273
+ The repository's [`example/`](https://github.com/trustpin-cloud/react-native.sdk/tree/main/example)
274
+ and [`example-expo/`](https://github.com/trustpin-cloud/react-native.sdk/tree/main/example-expo)
275
+ have an **Attestation** tab, next to the **Pinning** one: a protected call
276
+ with a token bound to the `Authorization` header, a sensitive call with an
277
+ assertion, sign-out and reset, with the SDK's state, events and logs in the
278
+ tab's own log.
279
+
280
+ ## License
281
+
282
+ See [LICENSE](LICENSE).
@@ -0,0 +1,33 @@
1
+ require "json"
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = "TrustPinReactNativeAttest"
7
+ s.version = package["version"]
8
+ s.summary = package["description"]
9
+ s.homepage = package["homepage"]
10
+ s.license = { :type => "Commercial", :file => "LICENSE" }
11
+ s.authors = package["author"]
12
+ s.source = { :git => "https://github.com/trustpin-cloud/react-native.sdk.git", :tag => "v#{s.version}" }
13
+
14
+ s.platforms = { :ios => "15.0" }
15
+ s.swift_version = "6.2"
16
+
17
+ s.source_files = "ios/**/*.{h,m,mm,swift}"
18
+ s.exclude_files = "ios/Tests/**/*"
19
+ # The ObjC++ adapter header imports the codegen spec (C++); keeping it out of
20
+ # the public umbrella lets Swift's underlying-module import compile the pod's
21
+ # ObjC module as plain ObjC.
22
+ s.private_header_files = ["ios/TrustPinReactNativeAttestModule.h"]
23
+ s.pod_target_xcconfig = { "DEFINES_MODULE" => "YES" }
24
+
25
+ # Native attestation module, locked to the 7.1.x line, the same line as
26
+ # @trustpin/react-native: it registers itself on the pinning SDK's default
27
+ # instance, so both resolve one TrustPinKit.
28
+ s.dependency "TrustPinAttestKit", "~> 7.1.0"
29
+ s.dependency "TrustPinKit", "~> 7.1.0"
30
+
31
+ # React Native core + New Architecture (TurboModule codegen) dependencies.
32
+ install_modules_dependencies(s)
33
+ end
@@ -0,0 +1,121 @@
1
+ def safeExtGet(prop, fallback) {
2
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
3
+ }
4
+
5
+ def requiredKotlinVersion = "2.3.0"
6
+
7
+ static def versionAtLeast(String actual, String required) {
8
+ def parse = { it.split("[.-]").findAll { p -> p.isInteger() }.collect { p -> p.toInteger() } }
9
+ def a = parse(actual)
10
+ def r = parse(required)
11
+ for (int i = 0; i < r.size(); i++) {
12
+ def left = i < a.size() ? a[i] : 0
13
+ if (left != r[i]) return left > r[i]
14
+ }
15
+ return true
16
+ }
17
+
18
+ apply plugin: "com.android.library"
19
+ apply plugin: "kotlin-android"
20
+
21
+ // The `cloud.trustpin:kotlin-attest` artifact is published with Kotlin 2.3.0
22
+ // binary metadata, so the compiler must be new enough to read it. Without this
23
+ // check the build fails with dozens of "incompatible version of Kotlin" errors
24
+ // that say nothing about how to fix them.
25
+ //
26
+ // This asks the applied Kotlin plugin for its own version rather than reading
27
+ // ext.kotlinVersion, which is unreliable in both directions: React Native's
28
+ // included Gradle build pins the plugin regardless of ext, and Expo sets ext
29
+ // from its own catalog even when the classpath carries a newer plugin.
30
+ def resolvedKotlinVersion
31
+ try {
32
+ resolvedKotlinVersion =
33
+ org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt.getKotlinPluginVersion(project)
34
+ } catch (Throwable ignored) {
35
+ resolvedKotlinVersion = safeExtGet("kotlinVersion", requiredKotlinVersion).toString()
36
+ }
37
+
38
+ if (!versionAtLeast(resolvedKotlinVersion.toString(), requiredKotlinVersion)) {
39
+ throw new GradleException(
40
+ "@trustpin/react-native-attest requires Kotlin ${requiredKotlinVersion} or newer, " +
41
+ "but this app builds with ${resolvedKotlinVersion}. The TrustPin Kotlin SDK is " +
42
+ "compiled with Kotlin ${requiredKotlinVersion} metadata. Pin the Kotlin plugin " +
43
+ "in your android/build.gradle buildscript classpath:\n" +
44
+ " classpath(\"org.jetbrains.kotlin:kotlin-gradle-plugin:${requiredKotlinVersion}\")\n" +
45
+ "(The Expo config plugin does this for you.)"
46
+ )
47
+ }
48
+ // Generates the TurboModule spec from package.json codegenConfig. This library
49
+ // is New Architecture only, so the plugin is always applied.
50
+ apply plugin: "com.facebook.react"
51
+
52
+ android {
53
+ namespace = "cloud.trustpin.reactnative.attest"
54
+
55
+ compileSdk = safeExtGet("compileSdkVersion", 36)
56
+
57
+ defaultConfig {
58
+ // 25 is the floor imposed by cloud.trustpin:kotlin-attest. Apps consuming
59
+ // this module must declare minSdk >= 25; the Expo config plugin raises
60
+ // it automatically with a warning.
61
+ minSdk = 25
62
+ }
63
+
64
+ compileOptions {
65
+ sourceCompatibility = JavaVersion.VERSION_17
66
+ targetCompatibility = JavaVersion.VERSION_17
67
+ }
68
+
69
+ kotlin {
70
+ compilerOptions {
71
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
72
+ }
73
+ }
74
+
75
+ sourceSets {
76
+ main.java.srcDirs += "src/main/kotlin"
77
+ test.java.srcDirs += "src/test/kotlin"
78
+ }
79
+
80
+ testOptions {
81
+ unitTests.all {
82
+ useJUnitPlatform()
83
+ }
84
+ unitTests.returnDefaultValues = true
85
+ }
86
+ }
87
+
88
+ repositories {
89
+ google()
90
+ mavenCentral()
91
+ }
92
+
93
+ dependencies {
94
+ // Version supplied by the consuming app's React Native Gradle plugin.
95
+ implementation "com.facebook.react:react-android"
96
+
97
+ // Pin the native modules to the 7.1.x patch line from 7.1.1, the same range as
98
+ // @trustpin/react-native: the attestation module registers itself on the
99
+ // pinning SDK's default instance, so both must resolve one kotlin-sdk.
100
+ // `strictly` prevents Gradle's conflict resolution from silently selecting
101
+ // a newer minor or major pulled in transitively by the consuming app.
102
+ //
103
+ // `api`: TrustPinReactNativeAttest.start's public overload takes a
104
+ // `TrustPinAttestLogLevel`, so consumers see that type.
105
+ api("cloud.trustpin:kotlin-attest") {
106
+ version {
107
+ strictly("[7.1.1, 7.2.0)")
108
+ }
109
+ }
110
+ implementation("cloud.trustpin:kotlin-sdk") {
111
+ version {
112
+ strictly("[7.1.1, 7.2.0)")
113
+ }
114
+ }
115
+
116
+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0"
117
+
118
+ testImplementation "org.jetbrains.kotlin:kotlin-test-junit5"
119
+ testImplementation "org.junit.jupiter:junit-jupiter:5.10.2"
120
+ testRuntimeOnly "org.junit.platform:junit-platform-launcher"
121
+ }
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,106 @@
1
+ package cloud.trustpin.reactnative.attest
2
+
3
+ /**
4
+ * Delivers the attestation module's state changes, events and logs to the
5
+ * TurboModule's emitters.
6
+ *
7
+ * Events and logs from before JavaScript exists (the native init helper runs
8
+ * in `Application.onCreate()`) wait in bounded buffers and replay once to the
9
+ * first JavaScript listener of each stream, as in `@trustpin/react-native`.
10
+ * State changes are live only: JavaScript reads the current state when it
11
+ * subscribes.
12
+ */
13
+ internal object AttestEventHub {
14
+
15
+ private const val CAPACITY = 32
16
+
17
+ private val lock = Any()
18
+
19
+ private val eventBuffer = ArrayDeque<Map<String, Any?>>()
20
+ private val logBuffer = ArrayDeque<Map<String, Any?>>()
21
+ private var eventsFlushed = false
22
+ private var logsFlushed = false
23
+
24
+ private var emitState: ((Map<String, Any?>) -> Unit)? = null
25
+ private var emitEvent: ((Map<String, Any?>) -> Unit)? = null
26
+ private var emitLog: ((Map<String, Any?>) -> Unit)? = null
27
+
28
+ fun recordState(state: Map<String, Any?>) {
29
+ val emit = synchronized(lock) { emitState }
30
+ emit?.invoke(state)
31
+ }
32
+
33
+ fun recordEvent(event: Map<String, Any?>) {
34
+ val emit = synchronized(lock) {
35
+ if (!eventsFlushed) {
36
+ append(eventBuffer, event)
37
+ return
38
+ }
39
+ emitEvent
40
+ }
41
+ emit?.invoke(event)
42
+ }
43
+
44
+ fun recordLog(log: Map<String, Any?>) {
45
+ val emit = synchronized(lock) {
46
+ if (!logsFlushed) {
47
+ append(logBuffer, log)
48
+ return
49
+ }
50
+ emitLog
51
+ }
52
+ emit?.invoke(log)
53
+ }
54
+
55
+ /** Called when the TurboModule is created; a reload replaces the callbacks. */
56
+ fun attach(
57
+ emitState: (Map<String, Any?>) -> Unit,
58
+ emitEvent: (Map<String, Any?>) -> Unit,
59
+ emitLog: (Map<String, Any?>) -> Unit,
60
+ ) {
61
+ synchronized(lock) {
62
+ this.emitState = emitState
63
+ this.emitEvent = emitEvent
64
+ this.emitLog = emitLog
65
+ }
66
+ }
67
+
68
+ fun flushEvents() = flush(eventBuffer, { eventsFlushed }, { eventsFlushed = true }, { emitEvent })
69
+
70
+ fun flushLogs() = flush(logBuffer, { logsFlushed }, { logsFlushed = true }, { emitLog })
71
+
72
+ private fun flush(
73
+ buffer: ArrayDeque<Map<String, Any?>>,
74
+ flushed: () -> Boolean,
75
+ markFlushed: () -> Unit,
76
+ emitter: () -> ((Map<String, Any?>) -> Unit)?,
77
+ ) {
78
+ val pending: List<Map<String, Any?>>
79
+ val emit: ((Map<String, Any?>) -> Unit)?
80
+ synchronized(lock) {
81
+ if (flushed()) return
82
+ markFlushed()
83
+ pending = buffer.toList()
84
+ emit = emitter()
85
+ buffer.clear()
86
+ }
87
+ pending.forEach { emit?.invoke(it) }
88
+ }
89
+
90
+ private fun append(buffer: ArrayDeque<Map<String, Any?>>, entry: Map<String, Any?>) {
91
+ if (buffer.size >= CAPACITY) buffer.removeFirst()
92
+ buffer.addLast(entry)
93
+ }
94
+
95
+ internal fun resetForTesting() {
96
+ synchronized(lock) {
97
+ eventBuffer.clear()
98
+ logBuffer.clear()
99
+ eventsFlushed = false
100
+ logsFlushed = false
101
+ emitState = null
102
+ emitEvent = null
103
+ emitLog = null
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,59 @@
1
+ package cloud.trustpin.reactnative.attest
2
+
3
+ import cloud.trustpin.kotlin.attest.TrustPinAttestError
4
+ import com.facebook.react.bridge.Arguments
5
+ import com.facebook.react.bridge.Promise
6
+ import com.facebook.react.bridge.WritableMap
7
+ import kotlinx.coroutines.CancellationException
8
+ import kotlinx.coroutines.CoroutineScope
9
+ import kotlinx.coroutines.launch
10
+
11
+ /** An argument JavaScript sent that the native module can't use. */
12
+ internal class AttestInvalidArgument(message: String) : Exception(message)
13
+
14
+ /** A rejection's code, message and reasons. */
15
+ internal data class AttestRejection(val code: String, val message: String?, val reasons: List<String>)
16
+
17
+ internal fun attestRejection(error: Throwable): AttestRejection = when (error) {
18
+ is CancellationException -> AttestRejection(AttestErrorCode.CANCELLED, "Operation was cancelled", emptyList())
19
+ is AttestInvalidArgument -> AttestRejection(AttestErrorCode.INVALID_ARGUMENTS, error.message, emptyList())
20
+ is TrustPinAttestError -> AttestRejection(error.code(), error.message, error.reasonList())
21
+ // `TrustPinAttest.instance(id)` and the configuration loader reject this way.
22
+ is IllegalArgumentException -> AttestRejection(AttestErrorCode.INVALID_CONFIGURATION, error.message, emptyList())
23
+ else -> AttestRejection(AttestErrorCode.ATTEST, error.message, emptyList())
24
+ }
25
+
26
+ /**
27
+ * Runs a module method: the suspending [operation] is launched on [scope] and
28
+ * its result, or its error with a stable code (an attestation failure's
29
+ * reasons in `userInfo.reasons`), delivered through [promise].
30
+ */
31
+ internal fun execute(scope: CoroutineScope, promise: Promise, operation: suspend () -> Any?) {
32
+ scope.launch {
33
+ try {
34
+ promise.resolve(operation())
35
+ } catch (e: Exception) {
36
+ val rejection = attestRejection(e)
37
+ val userInfo = Arguments.createMap().apply {
38
+ putArray(AttestKey.REASONS, Arguments.fromList(rejection.reasons))
39
+ }
40
+ promise.reject(rejection.code, rejection.message, userInfo)
41
+ if (e is CancellationException) throw e
42
+ }
43
+ }
44
+ }
45
+
46
+ /** Converts a map for the bridge. Numbers cross as doubles. */
47
+ internal fun Map<String, Any?>.toWritableMap(): WritableMap = Arguments.createMap().also { map ->
48
+ forEach { (key, value) ->
49
+ when (value) {
50
+ null -> map.putNull(key)
51
+ is Double -> map.putDouble(key, value)
52
+ is Long -> map.putDouble(key, value.toDouble())
53
+ is Int -> map.putInt(key, value)
54
+ is Boolean -> map.putBoolean(key, value)
55
+ is List<*> -> map.putArray(key, Arguments.fromList(value))
56
+ else -> map.putString(key, value.toString())
57
+ }
58
+ }
59
+ }