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

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.
@@ -0,0 +1,54 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.Manifest
4
+ import android.content.pm.PackageManager
5
+ import android.webkit.PermissionRequest
6
+ import android.webkit.WebChromeClient
7
+
8
+ private val RESOURCE_PERMISSIONS =
9
+ mapOf(
10
+ PermissionRequest.RESOURCE_VIDEO_CAPTURE to Manifest.permission.CAMERA,
11
+ PermissionRequest.RESOURCE_AUDIO_CAPTURE to Manifest.permission.RECORD_AUDIO,
12
+ )
13
+
14
+ /** Grants the app origin's media capture requests once the app holds their permissions. */
15
+ internal class TokamakWebChromeClient(
16
+ private val tokamak: TokamakApplication,
17
+ private val host: String,
18
+ ) : WebChromeClient() {
19
+ private val waiting = mutableSetOf<PermissionRequest>()
20
+
21
+ override fun onPermissionRequest(request: PermissionRequest) {
22
+ val supported = request.resources.all(RESOURCE_PERMISSIONS::containsKey)
23
+ if (!request.origin.isAppOrigin(host) || !supported) {
24
+ request.deny()
25
+ return
26
+ }
27
+ val missing = missingPermissions(request)
28
+ if (missing.isEmpty()) {
29
+ request.grant(request.resources)
30
+ return
31
+ }
32
+ waiting += request
33
+ try {
34
+ tokamak.permissionRequests.request(missing.toSet()) { if (waiting.remove(request)) decide(request) }
35
+ } catch (_: TokamakPluginError) {
36
+ waiting -= request
37
+ request.deny()
38
+ }
39
+ }
40
+
41
+ override fun onPermissionRequestCanceled(request: PermissionRequest) {
42
+ waiting -= request
43
+ }
44
+
45
+ private fun decide(request: PermissionRequest) {
46
+ if (missingPermissions(request).isEmpty()) request.grant(request.resources) else request.deny()
47
+ }
48
+
49
+ private fun missingPermissions(request: PermissionRequest): List<String> =
50
+ request.resources.map(RESOURCE_PERMISSIONS::getValue).filterNot(::isGranted)
51
+
52
+ private fun isGranted(permission: String): Boolean =
53
+ tokamak.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
54
+ }
@@ -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 (!uri.isAppOrigin(host)) {
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 || request.url.isAppOrigin(host)) 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) {
50
+ handler.proceed()
51
+ return
52
+ }
53
+ if (authority != null) android.util.Log.w("tokamak", "refused the gateway's certificate: $error")
54
+ handler.cancel()
55
+ }
56
+
57
+ override fun onReceivedClientCertRequest(view: WebView, request: ClientCertRequest) {
58
+ // Android reports no failure count, so every request is a first attempt.
59
+ val identity = runtime.clientIdentity(request.host, 0)
60
+ if (identity == null) {
61
+ // The gateway requires a certificate, so proceeding without one
62
+ // ends the connection, which is the intended outcome.
63
+ request.ignore()
64
+ return
65
+ }
66
+ val certificate = certificate(identity[0])
67
+ val privateKey = privateKey(identity[1])
68
+ if (certificate == null || privateKey == null) {
69
+ request.cancel()
70
+ return
71
+ }
72
+ request.proceed(privateKey, arrayOf(certificate))
73
+ }
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,73 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.hardware.biometrics.BiometricManager
4
+ import android.hardware.biometrics.BiometricManager.Authenticators
5
+ import android.hardware.biometrics.BiometricPrompt
6
+ import android.os.CancellationSignal
7
+
8
+ /**
9
+ * Throws unless the device owner can authenticate with [authenticators]: `NotSupportedError`
10
+ * without the hardware, otherwise `InvalidStateError`.
11
+ */
12
+ fun TokamakHost.requireOwnerAuthentication(authenticators: Int) {
13
+ when (context.getSystemService(BiometricManager::class.java).canAuthenticate(authenticators)) {
14
+ BiometricManager.BIOMETRIC_SUCCESS -> Unit
15
+ BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->
16
+ throw TokamakPluginError.notSupported("This device cannot perform the requested authentication")
17
+ else -> throw TokamakPluginError("InvalidStateError", "The requested authentication is not set up on this device")
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Shows the system prompt, titled [title], for the device owner to authenticate with
23
+ * [authenticators], authorising [crypto] when given. Calls [succeeded] once they do; otherwise
24
+ * [reply] receives the failure. Throws `NeedsUIError` while the app is in the background. Call it
25
+ * on the main thread.
26
+ */
27
+ fun TokamakHost.authenticateOwner(
28
+ title: CharSequence,
29
+ authenticators: Int,
30
+ crypto: BiometricPrompt.CryptoObject?,
31
+ reply: TokamakPluginReply,
32
+ succeeded: () -> Unit,
33
+ ) {
34
+ val activity = requireForegroundActivity()
35
+ val builder = BiometricPrompt.Builder(activity).setTitle(title).setAllowedAuthenticators(authenticators)
36
+ if ((authenticators and Authenticators.DEVICE_CREDENTIAL) == 0) {
37
+ builder.setNegativeButton(activity.getString(android.R.string.cancel), activity.mainExecutor) { _, _ ->
38
+ reply(Result.failure(TokamakPluginError("NotAllowedError", "Authentication was cancelled")))
39
+ }
40
+ }
41
+ val prompt = builder.build()
42
+ val callback = PromptCallback(reply, succeeded)
43
+ if (crypto == null) {
44
+ prompt.authenticate(CancellationSignal(), activity.mainExecutor, callback)
45
+ } else {
46
+ prompt.authenticate(crypto, CancellationSignal(), activity.mainExecutor, callback)
47
+ }
48
+ }
49
+
50
+ private class PromptCallback(
51
+ private val reply: TokamakPluginReply,
52
+ private val succeeded: () -> Unit,
53
+ ) : BiometricPrompt.AuthenticationCallback() {
54
+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) = succeeded()
55
+
56
+ override fun onAuthenticationError(code: Int, message: CharSequence) =
57
+ reply(Result.failure(TokamakPluginError(authenticationErrorName(code), message.toString())))
58
+ }
59
+
60
+ private fun authenticationErrorName(code: Int): String =
61
+ when (code) {
62
+ BiometricPrompt.BIOMETRIC_ERROR_CANCELED,
63
+ BiometricPrompt.BIOMETRIC_ERROR_USER_CANCELED,
64
+ BiometricPrompt.BIOMETRIC_ERROR_TIMEOUT,
65
+ BiometricPrompt.BIOMETRIC_ERROR_LOCKOUT,
66
+ BiometricPrompt.BIOMETRIC_ERROR_LOCKOUT_PERMANENT,
67
+ -> "NotAllowedError"
68
+ BiometricPrompt.BIOMETRIC_ERROR_NO_BIOMETRICS,
69
+ BiometricPrompt.BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL,
70
+ -> "InvalidStateError"
71
+ BiometricPrompt.BIOMETRIC_ERROR_HW_NOT_PRESENT -> "NotSupportedError"
72
+ else -> "OperationError"
73
+ }
@@ -0,0 +1,105 @@
1
+ package com.tokamak.runtime
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.content.Intent
6
+
7
+ /**
8
+ * A failure a plugin reports to the page as a `DOMException` named [errorName]. Other exceptions
9
+ * reach the page as an `OperationError`.
10
+ */
11
+ 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
+ fun typeError(message: String) = TokamakPluginError("TypeError", message)
19
+
20
+ /** UI was needed while the app is in the background, where it cannot show any. */
21
+ fun needsUI() = TokamakPluginError("NeedsUIError", "The app cannot show UI while it is in the background")
22
+ }
23
+ }
24
+
25
+ typealias TokamakPluginReply = (Result<Any?>) -> Unit
26
+
27
+ /**
28
+ * A native plugin, created once per process with the app's [TokamakHost]. A [call] or [subscribe]
29
+ * that throws replies with the exception.
30
+ */
31
+ interface TokamakPlugin {
32
+ val id: String
33
+
34
+ fun call(method: String, arguments: Any?, reply: TokamakPluginReply) {
35
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
36
+ }
37
+
38
+ fun subscribe(
39
+ method: String,
40
+ arguments: Any?,
41
+ reply: TokamakPluginReply,
42
+ ): () -> Unit {
43
+ reply(Result.failure(TokamakPluginError.notSupported("$id.$method is not supported")))
44
+ return {}
45
+ }
46
+
47
+ /** Receives the intent that started the app's activity, and each intent it receives later. */
48
+ fun onIntent(intent: Intent) = Unit
49
+ }
50
+
51
+ /** The app as one plugin sees it: its context, its activity, and its Worker. */
52
+ interface TokamakHost {
53
+ /** The application context. */
54
+ val context: Context
55
+
56
+ /** The app's activity, or null while it has none. */
57
+ val activity: Activity?
58
+
59
+ /** Whether the app is in the foreground, where it can show UI. Read it on the main thread. */
60
+ val isInForeground: Boolean
61
+
62
+ /**
63
+ * The activity to show UI in. Throws `NeedsUIError` while the app is in the background, where
64
+ * it cannot show UI. Call it on the main thread.
65
+ */
66
+ fun requireForegroundActivity(): Activity
67
+
68
+ /**
69
+ * Whether asking for [permission] shows the system prompt: the app does not hold it, and the
70
+ * user has not refused it for good. Call it on the main thread.
71
+ */
72
+ fun wouldPrompt(permission: String): Boolean
73
+
74
+ /**
75
+ * Asks the user for [permissions] in the app's activity once earlier requests finish, then
76
+ * passes [callback] whether each is granted. Answers at once, without UI, when none would
77
+ * prompt; throws `NeedsUIError` when one would while the app is in the background. Call it on
78
+ * the main thread; [callback] runs on the main thread.
79
+ */
80
+ fun requestPermissions(permissions: Set<String>, callback: (Map<String, Boolean>) -> Unit)
81
+
82
+ /**
83
+ * Delivers the plugin's event [name], which the Worker's listeners receive as
84
+ * `<plugin>.<name>`, with the JSON [event], and returns their reply as JSON, `null` when none
85
+ * replies. Starts the runtime when it is not running. Blocks, so call it off the main thread;
86
+ * throws unless the listeners return within [timeoutMillis], which includes runtime startup.
87
+ */
88
+ fun emit(name: String, event: String, timeoutMillis: Long): String
89
+
90
+ /**
91
+ * What the app serves at [path], as its WebView would load it: a file the app ships or the
92
+ * Worker's response. Starts the runtime when it is not running. Blocks, so call it off the main
93
+ * thread; throws unless it arrives within [timeoutMillis].
94
+ */
95
+ fun fetch(path: String, timeoutMillis: Long): ByteArray
96
+ }
97
+
98
+ /** The app's plugins. The app's [android.app.Application] is one. */
99
+ interface TokamakPlugins {
100
+ /** The plugin with [id], or null when the app does not include it. */
101
+ fun plugin(id: String): TokamakPlugin?
102
+ }
103
+
104
+ /** The plugin with [id] in the app this context belongs to, or null when the app does not include it. */
105
+ fun Context.tokamakPlugin(id: String): TokamakPlugin? = (applicationContext as TokamakPlugins).plugin(id)
@@ -0,0 +1,23 @@
1
+ package com.tokamak.runtime
2
+
3
+ import org.json.JSONObject
4
+
5
+ /** [arguments] as an object; throws a `TypeError` otherwise. */
6
+ fun requireObject(arguments: Any?): JSONObject =
7
+ arguments as? JSONObject ?: throw TokamakPluginError.typeError("arguments must be an object")
8
+
9
+ /** The string [name]; throws a `TypeError` otherwise. */
10
+ fun JSONObject.requireString(name: String): String =
11
+ optionalString(name) ?: throw TokamakPluginError.typeError("$name must be a string")
12
+
13
+ /** The string [name], or null when it is absent or null; throws a `TypeError` otherwise. */
14
+ fun JSONObject.optionalString(name: String): String? =
15
+ when (val value = opt(name)) {
16
+ null, JSONObject.NULL -> null
17
+ is String -> value
18
+ else -> throw TokamakPluginError.typeError("$name must be a string")
19
+ }
20
+
21
+ /** The boolean [name]; throws a `TypeError` otherwise. */
22
+ fun JSONObject.requireBoolean(name: String): Boolean =
23
+ opt(name) as? Boolean ?: throw TokamakPluginError.typeError("$name must be a boolean")
@@ -0,0 +1,33 @@
1
+ {
2
+ "tokamakVersion": "0.1.1",
3
+ "target": "android-arm64",
4
+ "variables": {
5
+ "key-alias": {
6
+ "kind": "string",
7
+ "description": "Alias of the signing key in the keystore"
8
+ },
9
+ "key-password": {
10
+ "kind": "string",
11
+ "description": "Password of the signing key; defaults to the keystore password"
12
+ },
13
+ "keystore": {
14
+ "kind": "path",
15
+ "description": "Keystore that signs release builds; without one, the debug key signs them"
16
+ },
17
+ "keystore-password": {
18
+ "kind": "string",
19
+ "description": "Password of the keystore"
20
+ },
21
+ "manifest": {
22
+ "kind": "path",
23
+ "description": "Partial AndroidManifest.xml merged over the generated manifest"
24
+ }
25
+ },
26
+ "pluginKeys": {
27
+ "class": "string",
28
+ "dependencies": "strings",
29
+ "manifest": "path",
30
+ "raw": "paths",
31
+ "sources": "paths"
32
+ }
33
+ }
package/package.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "@tokamakdev/platform-android-arm64",
3
+ "version": "0.1.1-beta.100",
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
+ }