@tokamakdev/platform-android-arm64 0.1.1-beta.38

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 (23) hide show
  1. package/android-arm64/bin/libtokamak.so +0 -0
  2. package/android-arm64/build/entrypoint +207 -0
  3. package/android-arm64/native-shell/TokamakActivity.kt +199 -0
  4. package/android-arm64/native-shell/TokamakPlugins.kt +183 -0
  5. package/android-arm64/native-shell/TokamakProxy.kt +65 -0
  6. package/android-arm64/native-shell/TokamakRuntime.kt +110 -0
  7. package/android-arm64/native-shell/TokamakWebViewClient.kt +103 -0
  8. package/android-arm64/platform-pack.json +21 -0
  9. package/android-arm64/tools/runtime/node_modules/@esbuild/darwin-arm64/README.md +3 -0
  10. package/android-arm64/tools/runtime/node_modules/@esbuild/darwin-arm64/bin/esbuild +0 -0
  11. package/android-arm64/tools/runtime/node_modules/@esbuild/darwin-arm64/package.json +20 -0
  12. package/android-arm64/tools/runtime/node_modules/@esbuild/darwin-x64/README.md +3 -0
  13. package/android-arm64/tools/runtime/node_modules/@esbuild/darwin-x64/bin/esbuild +0 -0
  14. package/android-arm64/tools/runtime/node_modules/@esbuild/darwin-x64/package.json +20 -0
  15. package/android-arm64/tools/runtime/node_modules/@esbuild/linux-x64/README.md +3 -0
  16. package/android-arm64/tools/runtime/node_modules/@esbuild/linux-x64/bin/esbuild +0 -0
  17. package/android-arm64/tools/runtime/node_modules/@esbuild/linux-x64/package.json +20 -0
  18. package/android-arm64/tools/runtime/node_modules/@esbuild/win32-x64/README.md +3 -0
  19. package/android-arm64/tools/runtime/node_modules/@esbuild/win32-x64/esbuild.exe +0 -0
  20. package/android-arm64/tools/runtime/node_modules/@esbuild/win32-x64/package.json +20 -0
  21. package/android-arm64/tools/runtime/node_modules/esbuild/LICENSE.md +21 -0
  22. package/android-arm64/tools/runtime/node_modules/esbuild/bin/esbuild +24 -0
  23. package/package.json +17 -0
Binary file
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ if [[ $# -ne 3 || $1 != build ]]; then
5
+ echo "usage: entrypoint build INPUT OUTPUT" >&2
6
+ exit 2
7
+ fi
8
+
9
+ input=$2
10
+ output=$3
11
+ metadata=$input/metadata
12
+ app_name=$(cat "$metadata/app-name")
13
+ host=$(cat "$metadata/host")
14
+ platform=$(cat "$metadata/platform")
15
+ identifier=$(cat "$metadata/identifier")
16
+ version=1.0
17
+ if [[ -f "$metadata/version" ]]; then
18
+ version=$(cat "$metadata/version")
19
+ fi
20
+ dev_endpoint=
21
+ dev_session_token=
22
+ if [[ -f "$metadata/dev-endpoint" ]]; then
23
+ dev_endpoint=$(cat "$metadata/dev-endpoint")
24
+ fi
25
+ if [[ -f "$metadata/dev-session-token" ]]; then
26
+ dev_session_token=$(cat "$metadata/dev-session-token")
27
+ fi
28
+ if [[ -n "$dev_endpoint" && -z "$dev_session_token" ]] || [[ -z "$dev_endpoint" && -n "$dev_session_token" ]]; then
29
+ echo "development endpoint and session token must be provided together" >&2
30
+ exit 1
31
+ fi
32
+ project=$(dirname "$output")/.tokamak
33
+ app=$project/app
34
+ native=$app/src/main/jniLibs/arm64-v8a
35
+ assets=$app/src/main/assets/app
36
+ kotlin=$app/src/main/kotlin/com/tokamak/runtime
37
+ plugins_root=$app/src/main/kotlin/tokamak/plugins
38
+ icons=$input/icons/$platform
39
+
40
+ xml_escape() {
41
+ printf '%s' "$1" |
42
+ sed -e 's/&/\&/g' \
43
+ -e 's/</\&lt;/g' \
44
+ -e 's/>/\&gt;/g' \
45
+ -e 's/"/\&quot;/g' \
46
+ -e "s/'/\&apos;/g"
47
+ }
48
+
49
+ rm -rf "$app/src/main/assets" "$app/src/main/jniLibs" "$app/src/main/kotlin" "$app/src/main/res" "$output"
50
+ mkdir -p "$native" "$assets" "$kotlin" "$plugins_root" "$app/src/main/res"
51
+ cp -R "$input/app/." "$assets/"
52
+ cp "$input/runtime/libtokamak.so" "$native/libtokamak.so"
53
+ cp -R "$input/native-shell/." "$kotlin/"
54
+
55
+ has_icon=false
56
+ if [[ -d "$icons" ]]; then
57
+ cp -R "$icons/." "$app/src/main/res/"
58
+ shopt -s nullglob
59
+ launcher_resources=("$app/src/main/res"/mipmap*/ic_launcher.*)
60
+ if (( ${#launcher_resources[@]} == 0 )); then
61
+ echo "Android icon resources must define mipmap/ic_launcher" >&2
62
+ exit 1
63
+ fi
64
+ has_icon=true
65
+ fi
66
+
67
+ shopt -s nullglob
68
+ plugin_classes=()
69
+ for plugin in "$input/plugins"/*; do
70
+ [[ -d "$plugin" ]] || continue
71
+ plugin_id=$(basename "$plugin")
72
+ plugin_classes+=("$(cat "$plugin/class")")
73
+ plugin_sources=$plugins_root/$plugin_id
74
+ mkdir -p "$plugin_sources"
75
+ for source in "$plugin/sources"/*; do
76
+ [[ -f "$source" ]] || continue
77
+ case "$source" in
78
+ *.kt)
79
+ cp "$source" "$plugin_sources/$(basename "$source")"
80
+ ;;
81
+ *)
82
+ echo "Android plugin source must be Kotlin: $source" >&2
83
+ exit 1
84
+ ;;
85
+ esac
86
+ done
87
+ done
88
+
89
+ mkdir -p "$project/app/src/main"
90
+ cat > "$project/settings.gradle" <<'EOF'
91
+ pluginManagement {
92
+ repositories {
93
+ google()
94
+ mavenCentral()
95
+ gradlePluginPortal()
96
+ }
97
+ }
98
+ dependencyResolutionManagement {
99
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
100
+ repositories {
101
+ google()
102
+ mavenCentral()
103
+ }
104
+ }
105
+ rootProject.name = 'tokamak'
106
+ include ':app'
107
+ EOF
108
+
109
+ cat > "$project/build.gradle" <<'EOF'
110
+ plugins {
111
+ id 'com.android.application' version '8.7.3' apply false
112
+ id 'org.jetbrains.kotlin.android' version '2.1.0' apply false
113
+ }
114
+ EOF
115
+
116
+ printf '%s\n' 'android.useAndroidX=true' > "$project/gradle.properties"
117
+ cat > "$project/app/build.gradle" <<EOF
118
+ plugins {
119
+ id 'com.android.application'
120
+ id 'org.jetbrains.kotlin.android'
121
+ }
122
+
123
+ android {
124
+ namespace 'com.tokamak.runtime'
125
+ compileSdk 35
126
+
127
+ defaultConfig {
128
+ applicationId '$identifier'
129
+ minSdk 31
130
+ targetSdk 35
131
+ versionCode 1
132
+ versionName '$version'
133
+ }
134
+
135
+ androidResources {
136
+ ignoreAssetsPattern = ''
137
+ }
138
+
139
+ sourceSets {
140
+ main {
141
+ kotlin.srcDirs += 'src/main/kotlin'
142
+ }
143
+ }
144
+
145
+ compileOptions {
146
+ sourceCompatibility JavaVersion.VERSION_17
147
+ targetCompatibility JavaVersion.VERSION_17
148
+ }
149
+ }
150
+
151
+ kotlin {
152
+ jvmToolchain(17)
153
+ }
154
+
155
+ dependencies {
156
+ implementation 'androidx.webkit:webkit:1.12.1'
157
+ }
158
+ EOF
159
+
160
+ registry=$kotlin/TokamakPluginRegistry.kt
161
+ {
162
+ printf '%s\n\n' 'package com.tokamak.runtime'
163
+ printf '%s\n\n' 'import android.app.Activity'
164
+ printf '%s\n' 'internal fun tokamakPlugins(activity: Activity): List<TokamakPlugin> ='
165
+ printf '%s\n' ' listOf('
166
+ if ((${#plugin_classes[@]} > 0)); then
167
+ for class in "${plugin_classes[@]}"; do
168
+ printf ' %s(activity),\n' "$class"
169
+ done
170
+ fi
171
+ printf '%s\n' ' )'
172
+ } > "$registry"
173
+
174
+ manifest=$app/src/main/AndroidManifest.xml
175
+ {
176
+ printf '%s\n' '<manifest xmlns:android="http://schemas.android.com/apk/res/android">'
177
+ printf '%s\n' ' <uses-permission android:name="android.permission.INTERNET" />'
178
+ for plugin in "$input/plugins"/*; do
179
+ [[ -d "$plugin" ]] || continue
180
+ for permission in "$plugin/permissions"/*; do
181
+ [[ -f "$permission" ]] || continue
182
+ printf ' <uses-permission android:name="%s" />\n' "$(cat "$permission")"
183
+ done
184
+ done
185
+ icon_attribute=
186
+ if [[ "$has_icon" == true ]]; then
187
+ icon_attribute=' android:icon="@mipmap/ic_launcher"'
188
+ fi
189
+ printf ' <application android:label="%s"%s android:usesCleartextTraffic="false">\n' "$(xml_escape "$app_name")" "$icon_attribute"
190
+ printf ' <meta-data android:name="tokamak.host" android:value="%s" />\n' "$host"
191
+ if [[ -n "$dev_endpoint" ]]; then
192
+ printf ' <meta-data android:name="tokamak.dev.endpoint" android:value="%s" />\n' "$dev_endpoint"
193
+ printf ' <meta-data android:name="tokamak.dev.session-token" android:value="%s" />\n' "$dev_session_token"
194
+ fi
195
+ printf '%s\n' ' <activity android:name=".TokamakActivity" android:exported="true" android:launchMode="singleTask" android:theme="@android:style/Theme.Material.NoActionBar" android:configChanges="colorMode|density|fontScale|keyboard|keyboardHidden|layoutDirection|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode">'
196
+ printf '%s\n' ' <intent-filter>'
197
+ printf '%s\n' ' <action android:name="android.intent.action.MAIN" />'
198
+ printf '%s\n' ' <category android:name="android.intent.category.LAUNCHER" />'
199
+ printf '%s\n' ' </intent-filter>'
200
+ printf '%s\n' ' </activity>'
201
+ printf '%s\n' ' </application>'
202
+ printf '%s\n' '</manifest>'
203
+ } > "$manifest"
204
+
205
+ gradle --no-daemon :app:assembleDebug --project-dir "$project"
206
+ mkdir -p "$(dirname "$output")"
207
+ cp "$app/build/outputs/apk/debug/app-debug.apk" "$output"
@@ -0,0 +1,199 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.app.Activity
4
+ import android.content.pm.PackageManager
5
+ import android.os.Bundle
6
+ import android.util.Log
7
+ import android.view.ViewGroup
8
+ import android.view.WindowInsets
9
+ import android.webkit.WebView
10
+ import android.widget.FrameLayout
11
+ import androidx.webkit.WebViewFeature
12
+ import java.io.File
13
+
14
+ private const val TAG = "tokamak"
15
+ private const val HOST_METADATA = "tokamak.host"
16
+ private const val DEV_ENDPOINT_METADATA = "tokamak.dev.endpoint"
17
+ private const val DEV_SESSION_TOKEN_METADATA = "tokamak.dev.session-token"
18
+ private const val STARTING = "<!doctype html><title>Starting</title>"
19
+ private const val FAILED =
20
+ "<!doctype html><title>tokamak</title><h1>App failed to start</h1><p>See logcat for details.</p>"
21
+ private const val UNSUPPORTED =
22
+ "<!doctype html><title>tokamak</title><h1>Unsupported WebView</h1>" +
23
+ "<p>This device's WebView cannot serve the app's secure origin.</p>"
24
+
25
+ /** The tokamak application: owns the window, WebView, and runtime lifecycle. */
26
+ class TokamakActivity : Activity() {
27
+ private lateinit var webView: WebView
28
+ private lateinit var pluginBridge: TokamakPluginBridge
29
+ private var runtime: TokamakRuntime? = null
30
+ private var proxyPort: Int? = null
31
+ private var restoreGeneration = 0L
32
+ private var destroyed = false
33
+
34
+ override fun onCreate(savedInstanceState: Bundle?) {
35
+ super.onCreate(savedInstanceState)
36
+ webView = WebView(this).apply {
37
+ settings.javaScriptEnabled = true
38
+ settings.domStorageEnabled = true
39
+ settings.setSupportMultipleWindows(false)
40
+ }
41
+ pluginBridge = TokamakPluginBridge(this, appHost(), tokamakPlugins(this))
42
+ if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
43
+ pluginBridge.install(webView)
44
+ }
45
+ setContentView(webViewContainer())
46
+ if (!proxyIsSupported()) {
47
+ show(UNSUPPORTED)
48
+ return
49
+ }
50
+ show(STARTING)
51
+ Thread(::startRuntime, "tokamak-startup").start()
52
+ }
53
+
54
+ override fun onResume() {
55
+ super.onResume()
56
+ restoreGeneration += 1
57
+ val generation = restoreGeneration
58
+ runtime?.let { restoreGateway(it, generation) }
59
+ }
60
+
61
+ override fun onDestroy() {
62
+ destroyed = true
63
+ restoreGeneration += 1
64
+ TokamakProxy.release(this)
65
+ pluginBridge.close()
66
+ webView.stopLoading()
67
+ webView.destroy()
68
+ runtime?.stop()
69
+ runtime = null
70
+ super.onDestroy()
71
+ }
72
+
73
+ override fun onRequestPermissionsResult(
74
+ requestCode: Int,
75
+ permissions: Array<out String>,
76
+ grantResults: IntArray,
77
+ ) {
78
+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)
79
+ pluginBridge.onRequestPermissionsResult(requestCode, permissions, grantResults)
80
+ }
81
+
82
+ private fun startRuntime() {
83
+ val started = runCatching { startConfiguredRuntime() }
84
+ runOnUiThread { finishStart(started) }
85
+ }
86
+
87
+ private fun startConfiguredRuntime(): TokamakRuntime {
88
+ val metadata = packageManager
89
+ .getApplicationInfo(packageName, PackageManager.GET_META_DATA)
90
+ .metaData
91
+ val endpoint = metadata?.getString(DEV_ENDPOINT_METADATA)
92
+ val sessionToken = metadata?.getString(DEV_SESSION_TOKEN_METADATA)
93
+ return if (!endpoint.isNullOrEmpty() && !sessionToken.isNullOrEmpty()) {
94
+ TokamakRuntime.startDevelopment(stateDir(), appHost(), endpoint, sessionToken)
95
+ } else {
96
+ TokamakRuntime.start(unpackApp(), stateDir(), appHost())
97
+ }
98
+ }
99
+
100
+ private fun finishStart(started: Result<TokamakRuntime>) {
101
+ if (destroyed) {
102
+ started.getOrNull()?.stop()
103
+ return
104
+ }
105
+ val runtime = started.getOrElse { error ->
106
+ Log.e(TAG, "tokamak failed to start", error)
107
+ show(FAILED)
108
+ return
109
+ }
110
+ this.runtime = runtime
111
+ proxyPort = runtime.port
112
+ TokamakProxy.acquire(this, appHost(), runtime.port)
113
+ }
114
+
115
+ private fun restoreGateway(runtime: TokamakRuntime, generation: Long) {
116
+ Thread {
117
+ val result = runCatching { runtime.restoreGateway() }
118
+ runOnUiThread {
119
+ if (
120
+ destroyed ||
121
+ this.runtime !== runtime ||
122
+ generation != restoreGeneration
123
+ ) return@runOnUiThread
124
+ result
125
+ .onSuccess { port ->
126
+ if (port != runtime.port) return@onSuccess
127
+ if (port != proxyPort) {
128
+ proxyPort = port
129
+ TokamakProxy.acquire(this, appHost(), port)
130
+ }
131
+ }
132
+ .onFailure { error ->
133
+ Log.w(TAG, "tokamak gateway could not recover", error)
134
+ }
135
+ }
136
+ }.start()
137
+ }
138
+
139
+ internal fun proxyReady() {
140
+ if (destroyed) return
141
+ val runtime = runtime ?: return
142
+ webView.webViewClient = TokamakWebViewClient(this, appHost(), runtime, pluginBridge)
143
+ webView.loadUrl("https://${appHost()}/")
144
+ }
145
+
146
+ private fun proxyIsSupported(): Boolean =
147
+ WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE) &&
148
+ WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE_REVERSE_BYPASS) &&
149
+ WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)
150
+
151
+ private fun show(html: String) = webView.loadData(html, "text/html", "utf-8")
152
+
153
+ private fun webViewContainer(): FrameLayout =
154
+ FrameLayout(this).apply {
155
+ addView(
156
+ webView,
157
+ FrameLayout.LayoutParams(
158
+ ViewGroup.LayoutParams.MATCH_PARENT,
159
+ ViewGroup.LayoutParams.MATCH_PARENT,
160
+ ),
161
+ )
162
+ setOnApplyWindowInsetsListener { view, insets ->
163
+ val bars = insets.getInsets(WindowInsets.Type.systemBars())
164
+ view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
165
+ insets
166
+ }
167
+ }
168
+
169
+ /** Copy the packaged app out of the APK so the runtime can read it as files. */
170
+ private fun unpackApp(): File {
171
+ val app = File(filesDir, "tokamak/app")
172
+ app.deleteRecursively()
173
+ copyAsset("app", app)
174
+ return app
175
+ }
176
+
177
+ private fun copyAsset(source: String, destination: File) {
178
+ val entries = assets.list(source) ?: emptyArray()
179
+ if (entries.isEmpty()) {
180
+ destination.parentFile?.mkdirs()
181
+ assets.open(source).use { input ->
182
+ destination.outputStream().use(input::copyTo)
183
+ }
184
+ return
185
+ }
186
+ destination.mkdirs()
187
+ for (entry in entries) copyAsset("$source/$entry", File(destination, entry))
188
+ }
189
+
190
+ private fun stateDir(): File = File(filesDir, "tokamak/state").apply { mkdirs() }
191
+
192
+ private fun appHost(): String {
193
+ val info = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
194
+ return requireNotNull(info.metaData?.getString(HOST_METADATA)) {
195
+ "$HOST_METADATA is required"
196
+ }
197
+ }
198
+
199
+ }
@@ -0,0 +1,183 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.app.Activity
4
+ import android.net.Uri
5
+ import android.webkit.WebView
6
+ import androidx.webkit.JavaScriptReplyProxy
7
+ import androidx.webkit.WebMessageCompat
8
+ import androidx.webkit.WebViewCompat
9
+ import org.json.JSONObject
10
+
11
+ internal class TokamakPluginError(
12
+ val errorName: String,
13
+ message: String,
14
+ ) : Exception(message) {
15
+ companion object {
16
+ fun notSupported(message: String) = TokamakPluginError("NotSupportedError", message)
17
+ }
18
+ }
19
+
20
+ internal typealias TokamakPluginReply = (Result<Any?>) -> Unit
21
+
22
+ internal interface TokamakPlugin {
23
+ val id: String
24
+
25
+ fun call(method: String, arguments: Any?, reply: TokamakPluginReply) {
26
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
27
+ }
28
+
29
+ fun subscribe(
30
+ method: String,
31
+ arguments: Any?,
32
+ reply: TokamakPluginReply,
33
+ ): () -> Unit {
34
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
35
+ return {}
36
+ }
37
+
38
+ fun onRequestPermissionsResult(
39
+ requestCode: Int,
40
+ permissions: Array<out String>,
41
+ grantResults: IntArray,
42
+ ) = Unit
43
+ }
44
+
45
+ internal class TokamakPluginBridge(
46
+ private val activity: Activity,
47
+ private val host: String,
48
+ plugins: List<TokamakPlugin>,
49
+ ) : WebViewCompat.WebMessageListener {
50
+ private data class RequestKey(val session: String, val id: Int)
51
+
52
+ private val plugins =
53
+ buildMap {
54
+ plugins.forEach { plugin ->
55
+ check(put(plugin.id, plugin) == null) { "Duplicate plugin ID" }
56
+ }
57
+ }
58
+ private val cancellations = mutableMapOf<RequestKey, () -> Unit>()
59
+ private var activeSession: String? = null
60
+
61
+ fun install(webView: WebView) {
62
+ WebViewCompat.addWebMessageListener(
63
+ webView,
64
+ "__tokamakNative",
65
+ setOf("https://$host"),
66
+ this,
67
+ )
68
+ }
69
+
70
+ fun close() {
71
+ activeSession = null
72
+ val cancelAll = cancellations.values.toList()
73
+ cancellations.clear()
74
+ cancelAll.forEach { it() }
75
+ }
76
+
77
+ fun onRequestPermissionsResult(
78
+ requestCode: Int,
79
+ permissions: Array<out String>,
80
+ grantResults: IntArray,
81
+ ) {
82
+ plugins.values.forEach {
83
+ it.onRequestPermissionsResult(requestCode, permissions, grantResults)
84
+ }
85
+ }
86
+
87
+ override fun onPostMessage(
88
+ view: WebView,
89
+ message: WebMessageCompat,
90
+ sourceOrigin: Uri,
91
+ isMainFrame: Boolean,
92
+ replyProxy: JavaScriptReplyProxy,
93
+ ) {
94
+ if (
95
+ !isMainFrame ||
96
+ sourceOrigin.scheme != "https" ||
97
+ sourceOrigin.host != host ||
98
+ (sourceOrigin.port != -1 && sourceOrigin.port != 443)
99
+ ) {
100
+ return
101
+ }
102
+ val request = runCatching { JSONObject(message.data ?: return) }.getOrNull() ?: return
103
+ val session = request.optString("session")
104
+ if (session.isEmpty()) return
105
+ if (request.optString("type") == "reset") {
106
+ close()
107
+ activeSession = session
108
+ return
109
+ }
110
+ val id = request.optInt("id", -1)
111
+ if (id < 0) return
112
+ val key = RequestKey(session, id)
113
+ when (request.optString("type")) {
114
+ "cancel" -> cancellations.remove(key)?.invoke()
115
+ "call", "subscribe" -> dispatch(request, key, replyProxy)
116
+ else ->
117
+ send(
118
+ replyProxy,
119
+ key,
120
+ Result.failure(
121
+ TokamakPluginError.notSupported("Plugin operation is not supported"),
122
+ ),
123
+ true,
124
+ )
125
+ }
126
+ }
127
+
128
+ private fun dispatch(
129
+ request: JSONObject,
130
+ key: RequestKey,
131
+ replyProxy: JavaScriptReplyProxy,
132
+ ) {
133
+ val plugin = plugins[request.optString("plugin")]
134
+ val method = request.optString("method")
135
+ if (plugin == null || method.isEmpty()) {
136
+ send(
137
+ replyProxy,
138
+ key,
139
+ Result.failure(TokamakPluginError.notSupported("Plugin is not supported")),
140
+ true,
141
+ )
142
+ return
143
+ }
144
+ val arguments = request.opt("arguments")
145
+ val reply: TokamakPluginReply = { result ->
146
+ send(replyProxy, key, result, request.optString("type") == "call")
147
+ }
148
+ if (request.optString("type") == "call") {
149
+ plugin.call(method, arguments, reply)
150
+ } else {
151
+ val cancellation = plugin.subscribe(method, arguments, reply)
152
+ cancellations[key] = cancellation
153
+ }
154
+ }
155
+
156
+ private fun send(
157
+ replyProxy: JavaScriptReplyProxy,
158
+ key: RequestKey,
159
+ result: Result<Any?>,
160
+ done: Boolean,
161
+ ) {
162
+ if (activeSession != key.session) return
163
+ val error = result.exceptionOrNull()
164
+ if (done) cancellations.remove(key)?.invoke()
165
+ val response =
166
+ JSONObject()
167
+ .put("session", key.session)
168
+ .put("id", key.id)
169
+ .put("done", done)
170
+ if (error == null) {
171
+ response.put("value", JSONObject.wrap(result.getOrNull()))
172
+ } else {
173
+ val name = (error as? TokamakPluginError)?.errorName ?: "UnknownError"
174
+ response.put(
175
+ "error",
176
+ JSONObject().put("name", name).put("message", error.message ?: name),
177
+ )
178
+ }
179
+ activity.runOnUiThread {
180
+ if (activeSession == key.session) replyProxy.postMessage(response.toString())
181
+ }
182
+ }
183
+ }
@@ -0,0 +1,65 @@
1
+ package com.tokamak.runtime
2
+
3
+ import androidx.webkit.ProxyConfig
4
+ import androidx.webkit.ProxyController
5
+
6
+ internal object TokamakProxy {
7
+ private var active: Request? = null
8
+ private var desired: Request? = null
9
+ private var changing = false
10
+
11
+ fun acquire(activity: TokamakActivity, host: String, port: Int) {
12
+ desired = Request(activity, host, port)
13
+ reconcile()
14
+ }
15
+
16
+ fun release(activity: TokamakActivity) {
17
+ if (desired?.activity === activity) desired = null
18
+ reconcile()
19
+ }
20
+
21
+ private fun reconcile() {
22
+ if (changing || active === desired) return
23
+ val current = active
24
+ if (current != null) {
25
+ clear(current)
26
+ return
27
+ }
28
+ desired?.let(::set)
29
+ }
30
+
31
+ private fun clear(request: Request) {
32
+ changing = true
33
+ ProxyController.getInstance().clearProxyOverride(request.activity.mainExecutor) {
34
+ active = null
35
+ changing = false
36
+ reconcile()
37
+ }
38
+ }
39
+
40
+ private fun set(request: Request) {
41
+ changing = true
42
+ ProxyController.getInstance().setProxyOverride(
43
+ proxyConfig(request),
44
+ request.activity.mainExecutor,
45
+ ) {
46
+ active = request
47
+ changing = false
48
+ if (desired === request) request.activity.proxyReady()
49
+ reconcile()
50
+ }
51
+ }
52
+
53
+ private fun proxyConfig(request: Request): ProxyConfig =
54
+ ProxyConfig.Builder()
55
+ .addProxyRule("http://127.0.0.1:${request.port}")
56
+ .addBypassRule(request.host)
57
+ .setReverseBypassEnabled(true)
58
+ .build()
59
+
60
+ private class Request(
61
+ val activity: TokamakActivity,
62
+ val host: String,
63
+ val port: Int,
64
+ )
65
+ }
@@ -0,0 +1,110 @@
1
+ package com.tokamak.runtime
2
+
3
+ import java.io.File
4
+
5
+ /** The tokamak runtime running in this process. */
6
+ internal class TokamakRuntime private constructor(private var handle: Long) {
7
+ private val lock = Any()
8
+
9
+ /** The loopback port the gateway bound. */
10
+ val port: Int
11
+ get() = synchronized(lock) { nativePort(requireHandle()) }
12
+
13
+ fun restoreGateway(): Int = synchronized(lock) {
14
+ nativeRestoreGateway(requireHandle())
15
+ }
16
+
17
+ fun suspend() = synchronized(lock) {
18
+ handle.takeIf { it != 0L }?.let(::nativeSuspend)
19
+ }
20
+
21
+ fun resume() = synchronized(lock) {
22
+ handle.takeIf { it != 0L }?.let(::nativeResume)
23
+ }
24
+
25
+ fun stop() = synchronized(lock) {
26
+ if (handle == 0L) return
27
+ val stopped = handle
28
+ handle = 0
29
+ nativeStop(stopped)
30
+ }
31
+
32
+ /**
33
+ * The authority a server certificate for [host] must chain to, or null
34
+ * when tokamak does not vouch for the host.
35
+ */
36
+ fun serverAuthority(host: String): ByteArray? = synchronized(lock) {
37
+ handle.takeIf { it != 0L }?.let { nativeServerAuthority(it, host) }
38
+ }
39
+
40
+ /**
41
+ * The client certificate and PKCS#8 private key, both DER, to present for
42
+ * [host]. Null when tokamak cannot authenticate the connection.
43
+ */
44
+ fun clientIdentity(host: String, previousFailures: Int): Array<ByteArray>? =
45
+ synchronized(lock) {
46
+ handle.takeIf { it != 0L }?.let {
47
+ nativeClientIdentity(it, host, previousFailures)
48
+ }
49
+ }
50
+
51
+ private fun requireHandle(): Long {
52
+ check(handle != 0L) { "tokamak runtime has stopped" }
53
+ return handle
54
+ }
55
+
56
+ companion object {
57
+ init {
58
+ System.loadLibrary("tokamak")
59
+ }
60
+
61
+ /** Start the runtime, throwing when it cannot serve the app. */
62
+ fun start(packagedDir: File, stateDir: File, host: String): TokamakRuntime =
63
+ TokamakRuntime(nativeStart(packagedDir.path, stateDir.path, host))
64
+
65
+ /** Start the runtime against a host development server. */
66
+ fun startDevelopment(
67
+ stateDir: File,
68
+ host: String,
69
+ endpoint: String,
70
+ sessionToken: String,
71
+ ): TokamakRuntime =
72
+ TokamakRuntime(nativeStartDevelopment(stateDir.path, host, endpoint, sessionToken))
73
+
74
+ @JvmStatic
75
+ private external fun nativeStart(packagedDir: String, stateDir: String, host: String): Long
76
+
77
+ @JvmStatic
78
+ private external fun nativeStartDevelopment(
79
+ stateDir: String,
80
+ host: String,
81
+ endpoint: String,
82
+ sessionToken: String,
83
+ ): Long
84
+
85
+ @JvmStatic
86
+ private external fun nativePort(handle: Long): Int
87
+
88
+ @JvmStatic
89
+ private external fun nativeRestoreGateway(handle: Long): Int
90
+
91
+ @JvmStatic
92
+ private external fun nativeSuspend(handle: Long)
93
+
94
+ @JvmStatic
95
+ private external fun nativeResume(handle: Long)
96
+
97
+ @JvmStatic
98
+ private external fun nativeStop(handle: Long)
99
+
100
+ @JvmStatic
101
+ private external fun nativeServerAuthority(handle: Long, host: String): ByteArray?
102
+
103
+ @JvmStatic
104
+ private external fun nativeClientIdentity(
105
+ handle: Long,
106
+ host: String,
107
+ previousFailures: Int,
108
+ ): Array<ByteArray>?
109
+ }
110
+ }
@@ -0,0 +1,103 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.app.Activity
4
+ import android.content.Intent
5
+ import android.graphics.Bitmap
6
+ import android.net.Uri
7
+ import android.net.http.SslError
8
+ import android.webkit.ClientCertRequest
9
+ import android.webkit.WebResourceRequest
10
+ import android.webkit.SslErrorHandler
11
+ import android.webkit.WebView
12
+ import android.webkit.WebViewClient
13
+ import java.io.ByteArrayInputStream
14
+ import java.security.KeyFactory
15
+ import java.security.PrivateKey
16
+ import java.security.cert.CertificateFactory
17
+ import java.security.cert.X509Certificate
18
+ import java.security.spec.PKCS8EncodedKeySpec
19
+
20
+ /** Answers the app origin's TLS challenges with the runtime's decision. */
21
+ internal class TokamakWebViewClient(
22
+ private val activity: Activity,
23
+ private val host: String,
24
+ private val runtime: TokamakRuntime,
25
+ private val pluginBridge: TokamakPluginBridge,
26
+ ) : WebViewClient() {
27
+ override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
28
+ pluginBridge.close()
29
+ val uri = Uri.parse(url)
30
+ if (!isAppOrigin(uri)) {
31
+ view.stopLoading()
32
+ openExternal(uri)
33
+ }
34
+ }
35
+
36
+ override fun shouldOverrideUrlLoading(
37
+ view: WebView,
38
+ request: WebResourceRequest,
39
+ ): Boolean {
40
+ if (!request.isForMainFrame || isAppOrigin(request.url)) return false
41
+ openExternal(request.url)
42
+ return true
43
+ }
44
+
45
+ override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
46
+ val host = Uri.parse(error.url).host
47
+ val authority = host?.let(runtime::serverAuthority)
48
+ val trusted = authority != null && chainsTo(error, authority)
49
+ if (trusted) handler.proceed() else handler.cancel()
50
+ }
51
+
52
+ override fun onReceivedClientCertRequest(view: WebView, request: ClientCertRequest) {
53
+ // Android reports no failure count, so every request is a first attempt.
54
+ val identity = runtime.clientIdentity(request.host, 0)
55
+ if (identity == null) {
56
+ // The gateway requires a certificate, so proceeding without one
57
+ // ends the connection, which is the intended outcome.
58
+ request.ignore()
59
+ return
60
+ }
61
+ val certificate = certificate(identity[0])
62
+ val privateKey = privateKey(identity[1])
63
+ if (certificate == null || privateKey == null) {
64
+ request.cancel()
65
+ return
66
+ }
67
+ request.proceed(privateKey, arrayOf(certificate))
68
+ }
69
+
70
+ private fun isAppOrigin(uri: Uri): Boolean =
71
+ uri.scheme.equals("https", ignoreCase = true) &&
72
+ uri.host?.equals(host, ignoreCase = true) == true &&
73
+ (uri.port == -1 || uri.port == 443)
74
+
75
+ private fun openExternal(uri: Uri) {
76
+ runCatching {
77
+ activity.startActivity(Intent(Intent.ACTION_VIEW, uri))
78
+ }.onFailure { error ->
79
+ android.util.Log.w("tokamak", "could not open external URL", error)
80
+ }
81
+ }
82
+
83
+ private fun chainsTo(error: SslError, authority: ByteArray): Boolean {
84
+ if (error.primaryError != SslError.SSL_UNTRUSTED) return false
85
+ val presented = error.certificate.x509Certificate ?: return false
86
+ val issuer = certificate(authority) ?: return false
87
+ return runCatching {
88
+ presented.checkValidity()
89
+ presented.verify(issuer.publicKey)
90
+ }.isSuccess
91
+ }
92
+
93
+ private fun certificate(der: ByteArray): X509Certificate? =
94
+ runCatching {
95
+ CertificateFactory.getInstance("X.509")
96
+ .generateCertificate(ByteArrayInputStream(der)) as X509Certificate
97
+ }.getOrNull()
98
+
99
+ private fun privateKey(der: ByteArray): PrivateKey? =
100
+ runCatching {
101
+ KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(der))
102
+ }.getOrNull()
103
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "tokamakVersion": "0.1.1",
3
+ "target": "android-arm64",
4
+ "artifacts": [
5
+ {
6
+ "kind": "runtimeLibrary",
7
+ "path": "bin/libtokamak.so"
8
+ },
9
+ {
10
+ "kind": "nativeShellDirectory",
11
+ "path": "native-shell"
12
+ },
13
+ {
14
+ "kind": "esbuildExecutable",
15
+ "path": "tools/runtime/node_modules/esbuild/bin/esbuild"
16
+ }
17
+ ],
18
+ "requiredTools": [
19
+ "gradle"
20
+ ]
21
+ }
@@ -0,0 +1,3 @@
1
+ # esbuild
2
+
3
+ This is the macOS ARM 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@esbuild/darwin-arm64",
3
+ "version": "0.28.1",
4
+ "description": "The macOS ARM 64-bit binary for esbuild, a JavaScript bundler.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/evanw/esbuild.git"
8
+ },
9
+ "license": "MIT",
10
+ "preferUnplugged": true,
11
+ "engines": {
12
+ "node": ">=18"
13
+ },
14
+ "os": [
15
+ "darwin"
16
+ ],
17
+ "cpu": [
18
+ "arm64"
19
+ ]
20
+ }
@@ -0,0 +1,3 @@
1
+ # esbuild
2
+
3
+ This is the macOS 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@esbuild/darwin-x64",
3
+ "version": "0.28.1",
4
+ "description": "The macOS 64-bit binary for esbuild, a JavaScript bundler.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/evanw/esbuild.git"
8
+ },
9
+ "license": "MIT",
10
+ "preferUnplugged": true,
11
+ "engines": {
12
+ "node": ">=18"
13
+ },
14
+ "os": [
15
+ "darwin"
16
+ ],
17
+ "cpu": [
18
+ "x64"
19
+ ]
20
+ }
@@ -0,0 +1,3 @@
1
+ # esbuild
2
+
3
+ This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@esbuild/linux-x64",
3
+ "version": "0.28.1",
4
+ "description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/evanw/esbuild.git"
8
+ },
9
+ "license": "MIT",
10
+ "preferUnplugged": true,
11
+ "engines": {
12
+ "node": ">=18"
13
+ },
14
+ "os": [
15
+ "linux"
16
+ ],
17
+ "cpu": [
18
+ "x64"
19
+ ]
20
+ }
@@ -0,0 +1,3 @@
1
+ # esbuild
2
+
3
+ This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@esbuild/win32-x64",
3
+ "version": "0.28.1",
4
+ "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/evanw/esbuild.git"
8
+ },
9
+ "license": "MIT",
10
+ "preferUnplugged": true,
11
+ "engines": {
12
+ "node": ">=18"
13
+ },
14
+ "os": [
15
+ "win32"
16
+ ],
17
+ "cpu": [
18
+ "x64"
19
+ ]
20
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Evan Wallace
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,24 @@
1
+ const { spawnSync } = require("node:child_process");
2
+ const path = require("node:path");
3
+
4
+ function esbuildPath(platform, arch) {
5
+ const hosts = ["darwin-arm64", "darwin-x64", "linux-x64", "win32-x64"];
6
+ const host = `${platform}-${arch}`;
7
+ if (!hosts.includes(host)) {
8
+ throw new Error(`tokamak does not provide esbuild for ${host}`);
9
+ }
10
+ const executable = platform === "win32" ? "esbuild.exe" : "bin/esbuild";
11
+ return path.resolve(__dirname, "../..", "@esbuild", host, executable);
12
+ }
13
+
14
+ if (require.main === module) {
15
+ const result = spawnSync(esbuildPath(process.platform, process.arch), process.argv.slice(2), {
16
+ stdio: "inherit",
17
+ });
18
+ if (result.error) {
19
+ throw result.error;
20
+ }
21
+ process.exit(result.status ?? 1);
22
+ }
23
+
24
+ module.exports = { esbuildPath };
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@tokamakdev/platform-android-arm64",
3
+ "version": "0.1.1-beta.38",
4
+ "description": "The tokamak platform pack for android-arm64",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/mantty/tokamak.git",
8
+ "directory": "tokamak-cli/npm/platform-packs/android-arm64"
9
+ },
10
+ "preferUnplugged": true,
11
+ "files": [
12
+ "android-arm64"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public"
16
+ }
17
+ }