Skip to content

Commit

Permalink
KTOR-409 Fix 'crypto is undefined' error in IE11 (#2531)
Browse files Browse the repository at this point in the history
  • Loading branch information
Stexxe authored Jun 26, 2021
1 parent 0821569 commit dc70b1b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
6 changes: 6 additions & 0 deletions ktor-utils/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ kotlin {
}
}

val jsTest by getting {
dependencies {
implementation(kotlin("test-js"))
}
}

// Hack: register the Native interop klibs as outputs of Kotlin source sets:
if (!ideaActive && rootProject.ext.get("native_targets_enabled") as Boolean) {
val utilsInterop by creating
Expand Down
10 changes: 6 additions & 4 deletions ktor-utils/js/src/io/ktor/util/CryptoJs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ public actual fun Digest(name: String): Digest = object : Digest {

// Variable is renamed to `_crypto` so it wouldn't clash with existing `crypto` variable.
// JS IR backend doesn't reserve names accessed inside js("") calls
private val _crypto: Crypto = if (PlatformUtils.IS_NODE) {
js("eval('require')('crypto')")
} else {
js("(crypto ? crypto : msCrypto)")
private val _crypto: Crypto by lazy { // lazy because otherwise it's untestable due to evaluation order
if (PlatformUtils.IS_NODE) {
js("eval('require')('crypto')")
} else {
js("(window.crypto ? window.crypto : window.msCrypto)")
}
}

private external class Crypto {
Expand Down
20 changes: 20 additions & 0 deletions ktor-utils/js/test/io.ktor.util/CryptoTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.util

import kotlin.test.*

class CryptoTest {

@Test
fun expectCryptoToBeDefinedInIE11() {
if (!PlatformUtils.IS_BROWSER) return

js("window.msCrypto = window.crypto")
js("Object.defineProperty(window, 'crypto', {writable: true})")
js("delete window.crypto")
assertEquals(16, generateNonce().length)
}
}

0 comments on commit dc70b1b

Please sign in to comment.