Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wasm target #56

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package org.publicvalue.convention.config

import org.gradle.api.JavaVersion
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import org.jetbrains.kotlin.gradle.targets.js.dsl.ExperimentalWasmDsl
import org.jetbrains.kotlin.gradle.targets.js.webpack.KotlinWebpackConfig
import org.publicvalue.convention.libs

fun KotlinMultiplatformExtension.configureAndroidTarget() {
Expand All @@ -14,6 +16,26 @@ fun KotlinMultiplatformExtension.configureAndroidTarget() {
}
}

@OptIn(ExperimentalWasmDsl::class)
fun KotlinMultiplatformExtension.configureWasm(baseName: String? = null) {
wasmJs {
moduleName = baseName ?: project.path.substring(1).replace(":","-").replace("-","_")
browser {
commonWebpackConfig {
outputFileName = "$baseName.js"
devServer = (devServer ?: KotlinWebpackConfig.DevServer()).apply {
static = (static ?: mutableListOf()).apply {
// Serve sources to debug inside browser
add(project.projectDir.path)
add(project.projectDir.path + "/commonMain/")
add(project.projectDir.path + "/wasmJsMain/")
}
}
}
}
}
}

fun KotlinMultiplatformExtension.configureIosTargets(baseName: String? = null) {
listOf(
iosX64(),
Expand Down
1 change: 1 addition & 0 deletions build-logic/settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ dependencyResolutionManagement {
mavenCentral()
google()
gradlePluginPortal()
maven("https://maven.pkg.jetbrains.space/public/p/ktor/eap")
}

versionCatalogs {
Expand Down
12 changes: 6 additions & 6 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ agp = "8.2.2"

#https://github.com/JetBrains/compose-multiplatform
compose-multiplatform = "1.5.11"
kotlin = "1.9.23"
kotlin = "2.0.0"
# https://github.com/google/ksp
ksp = "1.9.23-1.0.20"
kotlin-inject = "0.6.3"
Expand All @@ -26,20 +26,20 @@ coreKtx = "1.12.0"
#https://developer.android.com/jetpack/androidx/releases/arch-core
coreTesting = "2.2.0"

kotlinxCoroutines = "1.7.3"
kotlinxSerialization = "1.6.0"
kotlinxCoroutines = "1.8.1"
kotlinxSerialization = "1.7.0"

# https://github.com/Kotlin/kotlinx-datetime
kotlinxDatetime = "0.5.0"
kotlinxDatetime = "0.6.0"
# https://github.com/Kotlin/kotlinx-atomicfu
kotlinxAtomicfu = "0.23.1"
kotlinxAtomicfu = "0.24.0"

# https://github.com/slackhq/circuit/releases
circuit = "0.16.0"
sqldelight = "2.0.1"

okhttp = "4.12.0"
ktor = "2.3.7"
ktor = "3.0.0-beta-2-eap-949"

nexus-publish-plugin = "1.3.0"
multiplatform-swiftpackage = "2.2.0"
Expand Down
3,092 changes: 3,092 additions & 0 deletions kotlin-js-store/yarn.lock

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions oidc-appsupport/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import com.android.build.gradle.internal.tasks.factory.dependsOn
import org.jetbrains.kotlin.gradle.plugin.mpp.Framework
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
import org.publicvalue.convention.config.configureIosTargets
import org.publicvalue.convention.config.configureWasm
import java.nio.file.Files
import java.util.stream.Collectors.toList
import kotlin.io.path.name
Expand All @@ -15,11 +16,13 @@ plugins {

description = "Kotlin Multiplatform OIDC appsupport library for Android/iOS"


multiplatformSwiftPackage {
packageName("OpenIdConnectClient")
zipFileName("OpenIdConnectClient")
}


// workaround for https://forums.developer.apple.com/forums/thread/748177, remove once apple fixed it
val fixTask = tasks.create("fixFrameworkPlist") {
val fixTask = this
Expand Down Expand Up @@ -57,12 +60,14 @@ val fixTask = tasks.create("fixFrameworkPlist") {

}


afterEvaluate {
tasks.named("createXCFramework").dependsOn(tasks.named(fixTask.name))
}

kotlin {
configureIosTargets(baseName = "OpenIdConnectClient")
configureWasm(baseName = "OpenIdConnectClient")
sourceSets {
val commonMain by getting {
dependencies {
Expand All @@ -71,6 +76,7 @@ kotlin {
}
}


val iosMain by getting {
dependencies {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ actual class PlatformCodeAuthFlow(
client: OpenIdConnectClient,
) : CodeAuthFlow(client) {

override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse {
actual override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse {
val intent = Intent(
context,
HandleRedirectActivity::class.java
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package org.publicvalue.multiplatform.oidc.appsupport

import org.publicvalue.multiplatform.oidc.flows.AuthCodeResponse
import org.publicvalue.multiplatform.oidc.flows.CodeAuthFlow
import org.publicvalue.multiplatform.oidc.types.AuthCodeRequest

expect class PlatformCodeAuthFlow: CodeAuthFlow
expect class PlatformCodeAuthFlow: CodeAuthFlow {

override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ actual class PlatformCodeAuthFlow(
// required for swift (no default argument support)
constructor(client: OpenIdConnectClient) : this(client = client, ephemeralBrowserSession = false)

override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse = wrapExceptions {
actual override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse = wrapExceptions {
val authResponse = suspendCoroutine { continuation ->
val nsurl = NSURL.URLWithString(request.url.toString())
if (nsurl != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ actual class PlatformCodeAuthFlow(
var PORT = 8080
}

override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse {
actual override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse {

val redirectUrl = request.config.redirectUri?.let { Url(it) }
if (redirectUrl?.port != PORT || !redirectUrl.isLocalhost()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Webserver() {
}
}
}.apply {
server = this
server = engine
start(wait = true)
}
return call
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package org.publicvalue.multiplatform.oidc.appsupport

import io.ktor.http.*
import kotlinx.browser.window
import kotlinx.coroutines.delay
import org.publicvalue.multiplatform.oidc.OpenIdConnectClient
import org.publicvalue.multiplatform.oidc.OpenIdConnectException
import org.publicvalue.multiplatform.oidc.flows.AuthCodeResponse
import org.publicvalue.multiplatform.oidc.flows.AuthCodeResult
import org.publicvalue.multiplatform.oidc.flows.CodeAuthFlow
import org.publicvalue.multiplatform.oidc.types.AuthCodeRequest
import org.w3c.dom.Window


actual class PlatformCodeAuthFlow(
client: OpenIdConnectClient
) : CodeAuthFlow(client) {


actual override suspend fun getAuthorizationCode(request: AuthCodeRequest): AuthCodeResponse {
//window.location.replace(request.url.toString())
val loginWindow = window.open(request.url.toString())

// WAIT FOR EXTERNAL INPUT
val resultParameters = waitForRedirectUri(loginWindow)
return AuthCodeResponse.success(
AuthCodeResult(
code = resultParameters!!["code"],
state = resultParameters["state"]
)
)

}

suspend fun waitForRedirectUri(loginWindow: Window?): Parameters? {
while (true) {
var parameters: Parameters? = null
jsCatch {
kalinjul marked this conversation as resolved.
Show resolved Hide resolved
try {
val loginWindowUrl = Url(loginWindow?.location.toString())
if (loginWindowUrl.parameters.contains("code") && loginWindowUrl.parameters.contains("state")) {
println("Ok received all")
loginWindow?.close()
parameters = loginWindowUrl.parameters
} else {
println("Waiting")
}
} catch (e: Exception) {
println("I'm running, but login not completed")
}
}

if (parameters != null) {
return parameters
}

delay(100)
}
}

}

fun jsCatch(f: () -> Unit): JsAny? {
js("""
let result = null;
try {
f();
} catch (e) {
result = e;
}
return result;
""")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.publicvalue.multiplatform.oidc.appsupport

import org.publicvalue.multiplatform.oidc.OpenIdConnectClient
import kotlin.experimental.ExperimentalObjCRefinement


class WasmCodeAuthFlowFactory: CodeAuthFlowFactory {
override fun createAuthFlow(client: OpenIdConnectClient): PlatformCodeAuthFlow {
return PlatformCodeAuthFlow(client)
}
}
3 changes: 3 additions & 0 deletions oidc-core/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import org.publicvalue.convention.config.configureIosTargets
import org.publicvalue.convention.config.configureWasm

plugins {
id("org.publicvalue.convention.kotlin.multiplatform")
Expand All @@ -10,6 +11,7 @@ description = "Kotlin Multiplatform OIDC core library"

kotlin {
configureIosTargets()
configureWasm("oidc-core")
sourceSets {
val commonMain by getting {
dependencies {
Expand All @@ -31,6 +33,7 @@ kotlin {
}
}


val iosMain by getting {
dependencies {
implementation(libs.ktor.client.darwin)
Expand Down
6 changes: 6 additions & 0 deletions oidc-core/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import io.ktor.http.isSuccess
import io.ktor.http.parameters
import io.ktor.serialization.JsonConvertException
import io.ktor.serialization.kotlinx.KotlinxSerializationConverter
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.*
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import org.publicvalue.multiplatform.oidc.discovery.OpenIdConnectDiscover
Expand Down Expand Up @@ -59,6 +59,8 @@ class DefaultOpenIdConnectClient(

override var discoverDocument: OpenIdConnectConfiguration? = null

private val scope by lazy { CoroutineScope(Dispatchers.Default + SupervisorJob()) }

companion object {
val DefaultHttpClient by lazy {
HttpClient {
Expand Down Expand Up @@ -166,14 +168,14 @@ class DefaultOpenIdConnectClient(
config.clientSecret?.let { append("client_secret", it) }
if (config.codeChallengeMethod != CodeChallengeMethod.off) { append("code_verifier", authCodeRequest.pkce.codeVerifier) }
}
val request = runBlocking { // there is no suspending happening here
val request = scope.async { // there is no suspending happening here
Comment on lines -169 to +171
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you explain the difference between runBlocking and using a custom scope with await?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For a better async management

httpClient.prepareForm(
formParameters = formParameters
) {
url(url)
configure?.invoke(this)
}
}
}.await()
return TokenRequest(
request,
formParameters
Expand All @@ -191,14 +193,14 @@ class DefaultOpenIdConnectClient(
append("refresh_token", refreshToken)
config.scope?.let { append("scope", it) }
}
val request = runBlocking { // there is no suspending happening here
val request = scope.async { // there is no suspending happening here
httpClient.prepareForm(
formParameters = formParameters
) {
url(url)
configure?.invoke(this)
}
}
}.await()
return TokenRequest(
request,
formParameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,19 +133,19 @@ value class JwtClaims(

private fun JwtClaims.toOpenIdConnectToken(): IdToken =
IdToken(
iss = claims["iss"] as String?,
sub = claims["sub"] as String?,
iss = claims["iss"] as String,
sub = claims["sub"] as String,
aud = claims["aud"]?.parseListOrString(),
exp = claims["exp"] as Long?,
iat = claims["iat"] as Long?,
auth_time = claims["auth_time"] as Long?,
nonce = claims["nonce"] as String?,
acr = claims["acr"] as String?,
exp = claims["exp"] as Long,
iat = claims["iat"] as Long,
auth_time = claims["auth_time"] as? Long?,
nonce = claims["nonce"] as? String?,
acr = claims["acr"] as? String?,
amr = claims["amr"]?.parseListOrString(),
azp = claims["azp"] as String?,
alg = claims["alg"] as String?,
kid = claims["kid"] as String?,
at_hash = claims["at_hash"] as String?,
azp = claims["azp"] as? String?,
alg = claims["alg"] as? String?,
kid = claims["kid"] as? String?,
at_hash = claims["at_hash"] as? String?,
kalinjul marked this conversation as resolved.
Show resolved Hide resolved
additionalClaims = claims
)

Expand Down
Loading