@h1r-ai/croche-react-native 0.0.0-stage → 0.5.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 (77) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +486 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +8 -0
  6. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +837 -0
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
  9. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
  10. package/android/src/main/java/dev/croche/reactnative/ProjectTimeZone.kt +14 -0
  11. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  12. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  13. package/android/src/test/java/dev/croche/reactnative/ProjectTimeZoneTest.kt +24 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  16. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +32 -0
  17. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  18. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Croche.kt +120 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheAgent.kt +116 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +415 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +379 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectBinding.kt +79 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPalRouting.kt +25 -0
  32. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectPlatform.kt +46 -0
  33. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  34. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectTypes.kt +44 -0
  35. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  36. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  37. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +227 -0
  38. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  39. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  40. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  41. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  42. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  43. package/croche-react-native.podspec +28 -0
  44. package/ios/CrocheRuntimeBridge.swift +1008 -0
  45. package/ios/RNCrocheRuntime.mm +221 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  48. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  49. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +215 -0
  50. package/ios/vendor/CrocheRuntimeSDK/Host.swift +562 -0
  51. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  52. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  53. package/ios/vendor/CrocheRuntimeSDK/OpenOptions.swift +172 -0
  54. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  55. package/ios/vendor/CrocheRuntimeSDK/PortableSHA256.swift +42 -0
  56. package/ios/vendor/CrocheRuntimeSDK/Project.swift +271 -0
  57. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +558 -0
  58. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  59. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +453 -0
  60. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  61. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +345 -0
  62. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  63. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  64. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  65. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  66. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  67. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  68. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  69. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  70. package/package.json +40 -4
  71. package/scripts/vendor-native.sh +56 -0
  72. package/src/NativeCrocheRuntime.ts +162 -0
  73. package/src/index.ts +660 -0
  74. package/src/project-types.ts +35 -0
  75. package/src/project.ts +434 -0
  76. package/src/protocol.ts +28 -0
  77. package/src/types.ts +9 -0
@@ -0,0 +1,22 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+
9
+ class CrocheRuntimePackage : BaseReactPackage() {
10
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
11
+ if (name == CrocheRuntimeModule.NAME) CrocheRuntimeModule(reactContext) else null
12
+
13
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
14
+ mapOf(CrocheRuntimeModule.NAME to ReactModuleInfo(
15
+ CrocheRuntimeModule.NAME, CrocheRuntimeModule.NAME,
16
+ false, // canOverrideExistingModule
17
+ false, // needsEagerInit
18
+ false, // isCxxModule
19
+ true, // isTurboModule
20
+ ))
21
+ }
22
+ }
@@ -0,0 +1,17 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.JsonObject
4
+ import dev.croche.RuntimeAttestor
5
+
6
+ /** The project's attestor, shared by its agents: Play Integrity when the app gave its Cloud
7
+ * project number and did not turn attestation off; otherwise none (unverified). */
8
+ internal fun projectAttestor(options: JsonObject, playIntegrity: (Long) -> RuntimeAttestor): RuntimeAttestor? {
9
+ val number = options.getAsJsonObject("android")?.get("cloudProjectNumber")?.asLong
10
+ return if (options.get("attestation")?.asString != "off" && number != null) playIntegrity(number) else null
11
+ }
12
+
13
+ /** The host fields Core receives. They name the platform only when there is an attestor, as
14
+ * CrocheRuntime.create does: otherwise no agent asks to attest and every install registers
15
+ * unverified (sdk-internal #24). */
16
+ internal fun projectHost(options: JsonObject, attestor: RuntimeAttestor?): JsonObject =
17
+ options.getAsJsonObject("host").deepCopy().apply { attestor?.let { addProperty("attestationPlatform", it.platform) } }
@@ -0,0 +1,14 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.JsonObject
4
+ import dev.croche.CrocheException
5
+ import dev.croche.projectTimeZone
6
+ import java.util.TimeZone
7
+
8
+ /** Parse before CoreProject.open; never silently fall back to GMT for an unknown zone. */
9
+ internal fun projectZone(options: JsonObject): TimeZone? =
10
+ projectTimeZone(options.get("timeZone")?.takeUnless { it.isJsonNull }?.let {
11
+ if (!it.isJsonPrimitive || !it.asJsonPrimitive.isString)
12
+ throw CrocheException("invalid_configuration", "timeZone must be an IANA time zone")
13
+ it.asString
14
+ })
@@ -0,0 +1,49 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.JsonParser
4
+ import dev.croche.CrocheException
5
+ import dev.croche.ffi.CoreRuntimeInterface
6
+ import dev.croche.ffi.EventListener
7
+ import org.junit.Assert.*
8
+ import org.junit.Test
9
+ import java.lang.reflect.Proxy
10
+
11
+ class AgentMemoryTest {
12
+ @Test fun everyOperationUsesTheAgentCoreAndPreservesDeferredAndClosed() {
13
+ val calls = mutableListOf<Pair<String, List<Any?>>>()
14
+ var observer: EventListener? = null
15
+ var closed = false
16
+ val core = Proxy.newProxyInstance(CoreRuntimeInterface::class.java.classLoader,
17
+ arrayOf(CoreRuntimeInterface::class.java)) { _, method, args ->
18
+ if (closed) throw CrocheException("closed", "Agent is closed")
19
+ calls.add(method.name to (args?.toList() ?: emptyList()))
20
+ when (method.name) {
21
+ "memoryList" -> "[{\"id\":\"m1\"}]"
22
+ "memoryExport" -> "{\"enabled\":true,\"items\":[]}"
23
+ "setMemoryObserver" -> { observer = args?.get(0) as EventListener?; null }
24
+ else -> "{\"deferred\":true}"
25
+ }
26
+ } as CoreRuntimeInterface
27
+ val args = JsonParser.parseString("{\"id\":\"m1\",\"on\":true}").asJsonObject
28
+ val changes = mutableListOf<String>()
29
+ assertEquals("[{\"id\":\"m1\"}]", agentMemory(core, "list", args, changes::add))
30
+ assertEquals("{\"enabled\":true,\"items\":[]}", agentMemory(core, "export", args, changes::add))
31
+ for (op in listOf("delete", "clear", "enabled")) assertEquals("{\"deferred\":true}", agentMemory(core, op, args, changes::add))
32
+ assertEquals("null", agentMemory(core, "observe", args, changes::add))
33
+ // Don't enter UniFFI's thread attach hook from a pure JVM test; assert the listener is installed.
34
+ assertNotNull(observer)
35
+ assertEquals(listOf("memoryList", "memoryExport", "memoryDelete", "memoryClear", "memorySetEnabled", "setMemoryObserver"), calls.map { it.first })
36
+ assertEquals(listOf("m1"), calls.first { it.first == "memoryDelete" }.second)
37
+ assertEquals(listOf(true), calls.first { it.first == "memorySetEnabled" }.second)
38
+ args.addProperty("on", false)
39
+ agentMemory(core, "observe", args, changes::add)
40
+ assertNull(observer)
41
+ try { agentMemory(core, "set", args, changes::add); fail("set must be refused") }
42
+ catch (error: CrocheException) { assertEquals("invalid_memory", error.code); assertTrue(error.message!!.contains("memory.set")) }
43
+ closed = true
44
+ for (op in listOf("list", "delete", "clear", "enabled", "export", "observe")) {
45
+ try { agentMemory(core, op, args, changes::add); fail("closed $op must be refused") }
46
+ catch (error: CrocheException) { assertEquals("closed", error.code) }
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,42 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.JsonParser
4
+ import dev.croche.RuntimeAttestation
5
+ import dev.croche.RuntimeAttestor
6
+ import dev.croche.RuntimeCancellation
7
+ import org.junit.Assert.assertEquals
8
+ import org.junit.Assert.assertFalse
9
+ import org.junit.Assert.assertNull
10
+ import org.junit.Test
11
+
12
+ /** sdk-internal #24: the host fields the project API gives Core name the attestor's platform
13
+ * exactly when the bridge has an attestor. Core's side (it then attests at register) is the
14
+ * driver gate `project_a_host_naming_its_attestation_platform_attests_each_agent_at_register`. */
15
+ class ProjectAttestationTest {
16
+ private class Fake : RuntimeAttestor {
17
+ override val platform = "android-play-integrity"
18
+ override fun attest(clientData: String, clientDataHash: String, cancellation: RuntimeCancellation) = RuntimeAttestation("fixture")
19
+ }
20
+ private fun options(extra: String) =
21
+ JsonParser.parseString("""{"host":{"cloudUrl":"https://fixture.example","projectKey":"pk_fixture"}$extra}""").asJsonObject
22
+ private fun host(extra: String) = options(extra).let { projectHost(it, projectAttestor(it) { Fake() }) }
23
+
24
+ @Test fun aCloudProjectNumberGivesAnAttestorAndCoreHearsItsPlatform() {
25
+ val host = host(""","android":{"cloudProjectNumber":123}""")
26
+ assertEquals("android-play-integrity", host.get("attestationPlatform").asString)
27
+ assertEquals("pk_fixture", host.get("projectKey").asString)
28
+ }
29
+
30
+ @Test fun noCloudProjectNumberOrAttestationOffNamesNothing() {
31
+ for (extra in listOf("", ""","attestation":"off","android":{"cloudProjectNumber":123}""")) {
32
+ assertNull(projectAttestor(options(extra)) { Fake() })
33
+ assertFalse(extra, host(extra).has("attestationPlatform"))
34
+ }
35
+ }
36
+
37
+ @Test fun theOptionsAreNotChanged() {
38
+ val options = options(""","android":{"cloudProjectNumber":123}""")
39
+ projectHost(options, projectAttestor(options) { Fake() })
40
+ assertFalse(options.getAsJsonObject("host").has("attestationPlatform"))
41
+ }
42
+ }
@@ -0,0 +1,24 @@
1
+ package dev.croche.reactnative
2
+
3
+ import com.google.gson.JsonParser
4
+ import dev.croche.CrocheException
5
+ import org.junit.Assert.*
6
+ import org.junit.Test
7
+
8
+ class ProjectTimeZoneTest {
9
+ private fun options(json: String) = JsonParser.parseString(json).asJsonObject
10
+
11
+ @Test fun passedZoneChangesTheOffset() {
12
+ assertEquals(-600, projectZone(options("""{"timeZone":"Pacific/Honolulu"}"""))!!.getOffset(0) / 60_000)
13
+ }
14
+ @Test fun absentAndNullKeepTheDeviceZone() {
15
+ assertNull(projectZone(options("{}")))
16
+ assertNull(projectZone(options("""{"timeZone":null}""")))
17
+ }
18
+ @Test fun badZoneAndNonStringAreInvalidConfiguration() {
19
+ for (json in listOf("""{"timeZone":"Not/AZone"}""", """{"timeZone":42}""")) {
20
+ try { projectZone(options(json)); fail("Invalid timeZone accepted") }
21
+ catch (error: CrocheException) { assertEquals("invalid_configuration", error.code) }
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,133 @@
1
+ package dev.croche.android
2
+
3
+ import android.content.Context
4
+ import android.security.keystore.KeyGenParameterSpec
5
+ import android.security.keystore.KeyProperties
6
+ import com.google.android.gms.tasks.Tasks
7
+ import com.google.android.play.core.integrity.IntegrityManagerFactory
8
+ import com.google.android.play.core.integrity.IntegrityServiceException
9
+ import com.google.android.play.core.integrity.IntegrityTokenRequest
10
+ import com.google.gson.JsonObject
11
+ import com.google.gson.JsonParser
12
+ import dev.croche.CrocheException
13
+ import dev.croche.RuntimeAttestation
14
+ import dev.croche.RuntimeAttestor
15
+ import dev.croche.RuntimeCancellation
16
+ import dev.croche.RuntimeSecretStore
17
+ import java.io.File
18
+ import java.io.FileOutputStream
19
+ import java.security.GeneralSecurityException
20
+ import java.security.KeyStore
21
+ import java.util.concurrent.TimeUnit
22
+ import javax.crypto.Cipher
23
+ import javax.crypto.KeyGenerator
24
+ import javax.crypto.SecretKey
25
+ import javax.crypto.spec.GCMParameterSpec
26
+
27
+ // Android implementations of the Platform Abstraction Layer. See docs/MOBILE-SDK-AND-PAL.md.
28
+ // Not compiled on the Linux host (no Android SDK): build and run on the Mac before relying on it.
29
+
30
+ /**
31
+ * The Runtime credential, encrypted with an AES-GCM key that never leaves the Android
32
+ * Keystore, in the app's no-backup directory. Nothing here is backed up or restored: a
33
+ * restore to a new device, or a reinstall, starts without it, and the Core registers a new
34
+ * instance (the local conversation stays). Unlike the iOS Keychain, it does not survive
35
+ * uninstall. That asymmetry is by platform design; see the design document.
36
+ */
37
+ class KeystoreSecretStore(context: Context, name: String) : RuntimeSecretStore {
38
+ private val file = File(context.noBackupFilesDir, "croche/${name.replace(Regex("[^A-Za-z0-9._-]"), "_")}.secrets")
39
+
40
+ private fun key(): SecretKey {
41
+ val store = KeyStore.getInstance(KEYSTORE).apply { load(null) }
42
+ (store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
43
+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
44
+ generator.init(KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
45
+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
46
+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
47
+ .setKeySize(256)
48
+ .build())
49
+ return generator.generateKey()
50
+ }
51
+
52
+ @Synchronized override fun load(): JsonObject {
53
+ if (!file.exists()) return JsonObject()
54
+ val sealed = file.readBytes()
55
+ val plain = try {
56
+ if (sealed.size <= IV_BYTES) throw GeneralSecurityException("truncated")
57
+ Cipher.getInstance(TRANSFORMATION).run {
58
+ init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, sealed, 0, IV_BYTES))
59
+ doFinal(sealed, IV_BYTES, sealed.size - IV_BYTES)
60
+ }
61
+ } catch (_: GeneralSecurityException) {
62
+ // The key that sealed it is gone (Keystore cleared). The credential is lost, which
63
+ // the Core handles by registering a new instance; a stale blob must not block that.
64
+ file.delete(); return JsonObject()
65
+ }
66
+ val saved = try { JsonParser.parseString(String(plain, Charsets.UTF_8)) }
67
+ catch (_: Exception) { throw CrocheException("corrupt_store", "Runtime credentials are unreadable") }
68
+ if (!saved.isJsonObject) throw CrocheException("corrupt_store", "Runtime credentials must be an object")
69
+ return saved.asJsonObject
70
+ }
71
+
72
+ @Synchronized override fun remove() { java.nio.file.Files.deleteIfExists(file.toPath()) }
73
+
74
+ @Synchronized override fun save(secrets: JsonObject) {
75
+ val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, key()) }
76
+ val sealed = cipher.iv + cipher.doFinal(secrets.toString().toByteArray(Charsets.UTF_8))
77
+ check(cipher.iv.size == IV_BYTES) { "Unexpected GCM IV length" }
78
+ file.parentFile?.mkdirs()
79
+ val temporary = File(file.parentFile, file.name + ".tmp")
80
+ try {
81
+ FileOutputStream(temporary).use { output -> output.write(sealed); output.fd.sync() }
82
+ if (!temporary.renameTo(file)) throw CrocheException("storage_error", "Could not replace Runtime credentials")
83
+ } finally { temporary.delete() }
84
+ }
85
+
86
+ private companion object {
87
+ const val KEYSTORE = "AndroidKeyStore"
88
+ const val ALIAS = "croche.runtime.secrets"
89
+ const val TRANSFORMATION = "AES/GCM/NoPadding"
90
+ const val IV_BYTES = 12
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Google Play Integrity, classic request. Classic, not standard, because Cloud verifies the
96
+ * token locally with the response-encryption keys the developer downloads from Play Console;
97
+ * standard-request tokens can only be decrypted by Google's servers. The nonce is the Core's
98
+ * client data hash, so the verdict is bound to one Cloud challenge and one runtime identity.
99
+ *
100
+ * `cloudProjectNumber`: the Google Cloud project linked to the app in Play Console.
101
+ * Emulators and devices without Play Services cannot attest: use a development project.
102
+ */
103
+ class PlayIntegrityAttestor(context: Context, private val cloudProjectNumber: Long) : RuntimeAttestor {
104
+ private val manager = IntegrityManagerFactory.create(context.applicationContext)
105
+ override val platform = "android-play-integrity"
106
+
107
+ override fun attest(clientData: String, clientDataHash: String, cancellation: RuntimeCancellation): RuntimeAttestation {
108
+ cancellation.check()
109
+ // The nonce must be URL-safe, no-wrap Base64 of 16-500 characters; the 43-character
110
+ // unpadded hash qualifies. Cloud strips trailing '=' on both sides before comparing.
111
+ // Play allows 5 requests per app instance per minute: the Core makes one attest per
112
+ // registration attempt and never retries it on its own.
113
+ val request = IntegrityTokenRequest.builder().setNonce(clientDataHash).setCloudProjectNumber(cloudProjectNumber).build()
114
+ val response = try { Tasks.await(manager.requestIntegrityToken(request), 30, TimeUnit.SECONDS) }
115
+ catch (e: Exception) {
116
+ // Play's own error code (IntegrityErrorCode, e.g. -16 CLOUD_PROJECT_NUMBER_IS_INVALID,
117
+ // -1 API_NOT_AVAILABLE) is what a release setup is debugged with, and it carries no
118
+ // secret. The Core shows the host's code, not its message, so the number goes there.
119
+ val play = generateSequence<Throwable>(e) { it.cause }.filterIsInstance<IntegrityServiceException>().firstOrNull()
120
+ throw CrocheException(play?.let { "play_integrity_${it.errorCode}" } ?: "attestation_failed", "Play Integrity could not attest this app")
121
+ }
122
+ cancellation.check()
123
+ return RuntimeAttestation(response.token())
124
+ }
125
+ }
126
+
127
+ /** The wiki documents shipped in the app's assets under `folder` (`src/main/assets/wiki/`),
128
+ * paths relative to it: `CrocheRuntime.create(..., wiki = wikiFromAssets(context.assets))`. */
129
+ fun wikiFromAssets(assets: android.content.res.AssetManager, folder: String = "wiki"): List<dev.croche.WikiDocument> =
130
+ dev.croche.WikiDocument.fromTree(
131
+ list = { path -> assets.list(if (path.isEmpty()) folder else "$folder/$path") },
132
+ read = { path -> assets.open("$folder/$path").bufferedReader(Charsets.UTF_8).use { it.readText() } },
133
+ )
@@ -0,0 +1,47 @@
1
+ package dev.croche.android
2
+
3
+ import android.graphics.Bitmap
4
+ import android.graphics.BitmapFactory
5
+ import android.graphics.Matrix
6
+ import android.media.ExifInterface
7
+ import dev.croche.ImageCodec
8
+ import java.io.ByteArrayInputStream
9
+ import java.io.ByteArrayOutputStream
10
+ import kotlin.math.max
11
+ import kotlin.math.roundToInt
12
+
13
+ /**
14
+ * Standard images on Android (F30): decoded at the nearest power-of-two sample above the size
15
+ * (inSampleSize), scaled to at most `maxSide` px, turned upright by the EXIF orientation, and
16
+ * encoded as PNG and, when the bitmap has no alpha, JPEG at quality 70. The SDK finds it by name
17
+ * (`CrocheImages.codec`): an Android app needs no setup.
18
+ */
19
+ class BitmapImageCodec : ImageCodec {
20
+ override fun render(bytes: ByteArray, maxSide: Int): ImageCodec.Rendered? {
21
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
22
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
23
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
24
+ val longest = max(bounds.outWidth, bounds.outHeight)
25
+ var sample = 1
26
+ while (longest / (sample * 2) >= maxSide) sample *= 2
27
+ val decoded = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
28
+ ?: return null
29
+ val scale = minOf(1.0, maxSide.toDouble() / longest)
30
+ val width = max(1, (bounds.outWidth * scale).roundToInt())
31
+ val height = max(1, (bounds.outHeight * scale).roundToInt())
32
+ var bitmap = if (decoded.width != width || decoded.height != height) Bitmap.createScaledBitmap(decoded, width, height, true) else decoded
33
+ val degrees = try {
34
+ when (ExifInterface(ByteArrayInputStream(bytes)).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) {
35
+ ExifInterface.ORIENTATION_ROTATE_90 -> 90f
36
+ ExifInterface.ORIENTATION_ROTATE_180 -> 180f
37
+ ExifInterface.ORIENTATION_ROTATE_270 -> 270f
38
+ else -> 0f
39
+ }
40
+ } catch (_: Exception) { 0f }
41
+ if (degrees != 0f) bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, Matrix().apply { postRotate(degrees) }, true)
42
+ fun encode(format: Bitmap.CompressFormat, quality: Int) = ByteArrayOutputStream().also { bitmap.compress(format, quality, it) }.toByteArray()
43
+ val png = encode(Bitmap.CompressFormat.PNG, 100)
44
+ val jpeg = if (bitmap.hasAlpha()) null else encode(Bitmap.CompressFormat.JPEG, 70)
45
+ return ImageCodec.Rendered(png, jpeg, changed = scale < 1.0 || degrees != 0f)
46
+ }
47
+ }
@@ -0,0 +1,32 @@
1
+ package dev.croche.android
2
+
3
+ import android.content.ContentProvider
4
+ import android.content.ContentValues
5
+ import android.database.Cursor
6
+ import android.net.Uri
7
+ import java.io.File
8
+
9
+ /** Internal Android startup hook: the install's records use filesDir, regardless of its stores. */
10
+ internal class CrocheProjectRecordProvider : ContentProvider() {
11
+ override fun onCreate(): Boolean {
12
+ app = context?.applicationContext
13
+ location = app?.filesDir
14
+ return true
15
+ }
16
+ override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
17
+ override fun getType(uri: Uri): String? = null
18
+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null
19
+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
20
+ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
21
+
22
+ companion object {
23
+ @Volatile private var app: android.content.Context? = null
24
+ @Volatile private var location: File? = null
25
+ @JvmStatic fun directory(): File? = location
26
+ @JvmStatic fun language(): String = android.os.LocaleList.getDefault()[0].toLanguageTag()
27
+ @JvmStatic fun secretStorage(name: String): dev.croche.RuntimeSecretStore =
28
+ KeystoreSecretStore(checkNotNull(app) { "Croche startup provider is not initialized" }, name)
29
+ @JvmStatic fun attestor(number: Long): dev.croche.RuntimeAttestor =
30
+ PlayIntegrityAttestor(checkNotNull(app) { "Croche startup provider is not initialized" }, number)
31
+ }
32
+ }
@@ -0,0 +1,146 @@
1
+ package dev.croche.android
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.content.Context
6
+ import android.os.Bundle
7
+ import androidx.work.Constraints
8
+ import androidx.work.Data
9
+ import androidx.work.NetworkType
10
+ import androidx.work.OneTimeWorkRequestBuilder
11
+ import androidx.work.WorkInfo
12
+ import androidx.work.WorkManager
13
+ import androidx.work.Worker
14
+ import androidx.work.WorkerParameters
15
+ import dev.croche.CrocheException
16
+ import dev.croche.CrocheRuntime
17
+ import dev.croche.RuntimeCancellation
18
+ import dev.croche.RuntimeScheduler
19
+ import java.util.concurrent.TimeUnit
20
+
21
+ // The agent's scheduled notes on Android while the app is not running (founder 17:14Z): one
22
+ // waiting WorkManager request per Runtime, at the earliest note. Inexact: WorkManager runs it at
23
+ // or after its delay, when the device allows (Doze, App Standby buckets), with network. No exact
24
+ // alarms, no notifications, no permissions, no manifest entries.
25
+ // CI compiles it in the AAR job, and runs the scheduler against the real WorkManager on an
26
+ // emulator (examples/android-aar-sample, WorkManagerSchedulerTest); a delivery run needs a device.
27
+
28
+ /**
29
+ * Registers the earliest pending note as one `OneTimeWorkRequest`, tagged with `name`, whose
30
+ * worker runs `deliverDue()`. Pass it to `CrocheRuntime.create(..., scheduler = ...)`, and call
31
+ * `WorkManagerScheduler.install(application, name)` once in `Application.onCreate` so a run can
32
+ * reach that Runtime.
33
+ *
34
+ * A registration replaces only requests that are still waiting: it never cancels a run in
35
+ * progress, so a run that re-registers what is left (or whose delivery changes the pending set)
36
+ * never stops itself (rook, #323 A). Each Runtime uses its own `name`, and its runs deliver
37
+ * through the Runtime installed for that name; a second open Runtime with the same name is
38
+ * refused (`scheduler_conflict`), including a second Runtime given this same object.
39
+ */
40
+ class WorkManagerScheduler(context: Context, val name: String = DEFAULT_NAME) : RuntimeScheduler {
41
+ private val context = context.applicationContext
42
+
43
+ override fun schedule(earliestAtMs: Long) = synchronized(lockFor(name)) {
44
+ val manager = manager()
45
+ val request = OneTimeWorkRequestBuilder<CrocheDeliveryWorker>()
46
+ .setInitialDelay((earliestAtMs - System.currentTimeMillis()).coerceAtLeast(0), TimeUnit.MILLISECONDS)
47
+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
48
+ .setInputData(Data.Builder().putString(KEY_NAME, name).build())
49
+ .addTag(tag(name))
50
+ .build()
51
+ withdrawWaiting(manager)
52
+ manager.enqueue(request)
53
+ Unit
54
+ }
55
+
56
+ override fun cancel() = synchronized(lockFor(name)) { withdrawWaiting(manager()) }
57
+
58
+ /** One open Runtime per name, this scheduler object included: `create` attaches once per
59
+ * Runtime, so a second attach while the name is held (by another object, or by this one for
60
+ * another open Runtime) is refused (Atlas, #323 at dc38bf0). Close-and-reuse stays valid. */
61
+ override fun attach() = claims.claim(name, this)
62
+
63
+ override fun detach() = claims.release(name, this)
64
+
65
+ /** Cancels this name's requests that are waiting (enqueued, or blocked), never one that runs. */
66
+ private fun withdrawWaiting(manager: WorkManager) {
67
+ val infos = try { manager.getWorkInfosByTag(tag(name)).get() } catch (_: Exception) { emptyList() }
68
+ for (id in waiting(infos.map { it.id to it.state })) manager.cancelWorkById(id)
69
+ }
70
+
71
+ private fun manager(): WorkManager = try { WorkManager.getInstance(context) }
72
+ // The app turned WorkManager's initializer off without providing a Configuration.
73
+ catch (_: IllegalStateException) { throw CrocheException("not_configured", "WorkManager is not initialized in this app") }
74
+
75
+ companion object {
76
+ const val DEFAULT_NAME = "croche.schedule"
77
+ internal const val KEY_NAME = "dev.croche.schedule.name"
78
+ private val claims = dev.croche.SchedulerClaims("WorkManager name")
79
+ private val locks = java.util.concurrent.ConcurrentHashMap<String, Any>()
80
+ private fun lockFor(name: String) = locks.getOrPut(name) { Any() }
81
+ internal val providers = java.util.concurrent.ConcurrentHashMap<String, (Context) -> CrocheRuntime?>()
82
+
83
+ /** The tag that marks `name`'s requests. */
84
+ fun tag(name: String) = "dev.croche.schedule:$name"
85
+
86
+ /** Of these requests, the ones a registration may cancel: those still waiting. Never a
87
+ * running one, which may be the very run registering. */
88
+ fun <T> waiting(requests: List<Pair<T, WorkInfo.State>>): List<T> =
89
+ requests.filter { (_, state) -> state == WorkInfo.State.ENQUEUED || state == WorkInfo.State.BLOCKED }.map { it.first }
90
+
91
+ /** What `name`'s WorkManager runs deliver through: the app's Runtime, opened if need be,
92
+ * or null when there is none to reach (the run ends; the next open delivers). A run never
93
+ * closes it. */
94
+ fun deliverThrough(name: String = DEFAULT_NAME, runtime: (Context) -> CrocheRuntime?) { providers[name] = runtime }
95
+
96
+ /**
97
+ * `deliverThrough(name, runtime)`, and a delivery at each return to the foreground (the
98
+ * first activity started), off the main thread. Call once per name in
99
+ * `Application.onCreate`.
100
+ */
101
+ fun install(application: Application, name: String = DEFAULT_NAME, runtime: (Context) -> CrocheRuntime) {
102
+ deliverThrough(name, runtime)
103
+ application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
104
+ private var started = 0
105
+ override fun onActivityStarted(activity: Activity) {
106
+ if (started++ == 0) Thread({ try { runtime(application).deliverDue() } catch (_: Exception) {} }, "croche-foreground").start()
107
+ }
108
+ override fun onActivityStopped(activity: Activity) { started = (started - 1).coerceAtLeast(0) }
109
+ override fun onActivityCreated(activity: Activity, state: Bundle?) {}
110
+ override fun onActivityResumed(activity: Activity) {}
111
+ override fun onActivityPaused(activity: Activity) {}
112
+ override fun onActivitySaveInstanceState(activity: Activity, state: Bundle) {}
113
+ override fun onActivityDestroyed(activity: Activity) {}
114
+ })
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * One WorkManager run: `deliverDue()` through the Runtime installed for its name.
121
+ *
122
+ * It always ends `success`: the Runtime has already registered what is still pending (a request
123
+ * of its own, never this one), so a WorkManager retry would only add a second request. A
124
+ * delivery already in flight (`inFlight`) ends it at once, with nothing registered: the
125
+ * delivery in flight registers what is left when it ends (rook, #323 B). Only a Runtime that
126
+ * could not be opened asks WorkManager to retry.
127
+ *
128
+ * When WorkManager stops the run (its time is up, or the constraints are lost), this run's own
129
+ * delivery is cancelled, whether it is waiting behind another turn or running: never another
130
+ * turn of the Runtime. Its notes stay pending, and registered.
131
+ */
132
+ class CrocheDeliveryWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
133
+ private val cancellation = RuntimeCancellation()
134
+
135
+ override fun doWork(): Result {
136
+ val name = inputData.getString(WorkManagerScheduler.KEY_NAME) ?: WorkManagerScheduler.DEFAULT_NAME
137
+ // Not installed for this name: the next open delivers.
138
+ val open = WorkManagerScheduler.providers[name] ?: return Result.success()
139
+ val runtime = try { open(applicationContext) } catch (_: Exception) { return Result.retry() } ?: return Result.success()
140
+ if (isStopped) return Result.success()
141
+ try { runtime.deliverDue(cancellation) } catch (_: Exception) { /* registered again by the Runtime */ }
142
+ return Result.success()
143
+ }
144
+
145
+ override fun onStopped() { cancellation.cancel() }
146
+ }
@@ -0,0 +1,9 @@
1
+ # Preserve native mappings for JNA's Android AAR; no Kotlin reflection is used by Gson.
2
+ -dontwarn java.awt.*
3
+ -keep class com.sun.jna.** { *; }
4
+ -keep class * extends com.sun.jna.** { *; }
5
+ # The UniFFI bindings: JNA reads their Structure fields and callback interfaces reflectively.
6
+ -keep class dev.croche.ffi.** { *; }
7
+
8
+ # The JVM host discovers Android's app-private project location through this startup hook.
9
+ -keep class dev.croche.android.CrocheProjectRecordProvider { public static java.io.File directory(); public static java.lang.String language(); public static dev.croche.RuntimeSecretStore secretStorage(java.lang.String); public static dev.croche.RuntimeAttestor attestor(long); }
@@ -0,0 +1,110 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.GsonBuilder
4
+ import com.google.gson.TypeAdapter
5
+ import com.google.gson.stream.JsonReader
6
+ import com.google.gson.stream.JsonWriter
7
+ import kotlinx.coroutines.channels.Channel
8
+ import java.time.Instant
9
+
10
+ /** Isolated serial delivery, bounded including the event currently in the collector. */
11
+ internal class AppStreamBranch {
12
+ private data class Item(val event: RuntimeEvent, val bytes: Int)
13
+ private val lock = Any()
14
+ private val wake = Channel<Unit>(Channel.CONFLATED)
15
+ private val queue = ArrayDeque<Item>()
16
+ private var count = 0
17
+ private var bytes = 0
18
+ private var ended = false
19
+ private var terminal: RuntimeEvent? = null
20
+ val isEnded get() = synchronized(lock) { ended }
21
+
22
+ /** Core-delivered events stay ordered, including a final StreamError behind the backlog. */
23
+ fun push(event: RuntimeEvent) = synchronized(lock) {
24
+ if (ended) return@synchronized
25
+ val item = try {
26
+ val json = event.serialized()
27
+ Item(event.owned(), json.toByteArray(Charsets.UTF_8).size)
28
+ } catch (failure: Exception) {
29
+ end(RuntimeEvent.StreamError("handler_failed", "Event could not be queued", false))
30
+ return@synchronized
31
+ }
32
+ if (count + 1 > 256 || bytes.toLong() + item.bytes > 1_048_576) {
33
+ end(RuntimeEvent.StreamError("subscriber_overflow", "Collector fell behind", false))
34
+ return@synchronized
35
+ }
36
+ queue.addLast(item)
37
+ count++
38
+ bytes += item.bytes
39
+ if (event is RuntimeEvent.StreamError || event === RuntimeEvent.Replaced) ended = true
40
+ wake.trySend(Unit)
41
+ }
42
+ /** SDK-side termination drops queued work; an in-flight delivery settles before last. */
43
+ fun end(last: RuntimeEvent? = null) = synchronized(lock) {
44
+ if (ended) return@synchronized
45
+ ended = true
46
+ queue.clear()
47
+ terminal = last
48
+ wake.trySend(Unit)
49
+ }
50
+ fun close() = end()
51
+
52
+ suspend fun deliver(emit: suspend (RuntimeEvent) -> Unit) {
53
+ while (true) {
54
+ val delivery = synchronized(lock) { Triple(queue.removeFirstOrNull(), ended, terminal) }
55
+ val item = delivery.first
56
+ if (item != null) {
57
+ // Flow's downstream exception/cancellation belongs to the collecting coroutine.
58
+ // The Kotlin page explicitly requires a downstream collector exception to
59
+ // leave collect and detach only this branch; never emit after that exception.
60
+ try { emit(item.event) }
61
+ finally { synchronized(lock) { count--; bytes -= item.bytes } }
62
+ continue
63
+ }
64
+ if (delivery.second) {
65
+ delivery.third?.let { emit(it) }
66
+ return
67
+ }
68
+ wake.receive()
69
+ }
70
+ }
71
+ }
72
+
73
+ private val eventJson = GsonBuilder().disableHtmlEscaping().registerTypeAdapter(Instant::class.java, object : TypeAdapter<Instant>() {
74
+ override fun write(out: JsonWriter, value: Instant?) { if (value == null) out.nullValue() else out.value(value.toString()) }
75
+ override fun read(input: JsonReader): Instant = Instant.parse(input.nextString())
76
+ }).create()
77
+
78
+ /** Copy nested app-owned containers; Page requires recursive copying of polymorphic messages. */
79
+ internal fun RuntimeEvent.owned(): RuntimeEvent = when (this) {
80
+ is RuntimeEvent.Input -> copy(images = images.toList())
81
+ is RuntimeEvent.MessageEnd -> copy(markers = markers.toList(), output = output?.deepCopy(), inReplyTo = inReplyTo.toList(), causedBy = causedBy.toList())
82
+ is RuntimeEvent.App -> copy(data = data.deepCopy())
83
+ is RuntimeEvent.Turn -> copy(causedBy = causedBy.toList(), inputs = inputs.toList(), usage = usage.toMap())
84
+ is RuntimeEvent.Error -> copy(inputs = inputs.toList())
85
+ is RuntimeEvent.Page -> copy(messages = messages.map { it.owned() })
86
+ else -> this
87
+ }
88
+
89
+ /** Tagged delivery payload, UTF-8 bytes including event structure as in S2's queue. */
90
+ internal fun RuntimeEvent.serialized(): String {
91
+ val json = eventJson.toJsonTree(this).asJsonObject
92
+ val type = when (this) {
93
+ is RuntimeEvent.Input -> "input"
94
+ is RuntimeEvent.MessageStart -> "message.start"
95
+ is RuntimeEvent.MessageDelta -> "message.delta"
96
+ is RuntimeEvent.MessageEnd -> "message.end"
97
+ is RuntimeEvent.Cleared -> "cleared"
98
+ is RuntimeEvent.App -> "app"
99
+ is RuntimeEvent.Turn -> "turn"
100
+ is RuntimeEvent.Error, is RuntimeEvent.StreamError -> "error"
101
+ is RuntimeEvent.State -> "state"
102
+ is RuntimeEvent.Page -> "page"
103
+ is RuntimeEvent.Gap -> "gap"
104
+ is RuntimeEvent.Snapshot -> "snapshot"
105
+ RuntimeEvent.Replaced -> "replaced"
106
+ is RuntimeEvent.Unknown -> this.type
107
+ }
108
+ json.addProperty("type", type)
109
+ return eventJson.toJson(json)
110
+ }