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

KTOR-6158 JS. Remove redundant require call for crypto #4434

Merged
merged 2 commits into from
Oct 30, 2024
Merged
Changes from all 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
17 changes: 2 additions & 15 deletions ktor-utils/jsAndWasmShared/src/io/ktor/util/CryptoJs.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ import kotlin.js.*
*/
public actual fun generateNonce(): String {
val buffer = ByteArray(NONCE_SIZE_IN_BYTES).toJsArray()
when {
PlatformUtils.IS_NODE -> _crypto.randomFillSync(buffer)
else -> _crypto.getRandomValues(buffer)
}
_crypto.getRandomValues(buffer)
return hex(buffer.toByteArray())
}

Expand All @@ -41,24 +38,14 @@ public actual fun Digest(name: String): Digest = object : Digest {
}
}

private fun requireCrypto(): Crypto = js("eval('require')('crypto')")
private fun windowCrypto(): Crypto = js("(window ? (window.crypto ? window.crypto : window.msCrypto) : self.crypto)")

// 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 by lazy { // lazy because otherwise it's untestable due to evaluation order
when {
PlatformUtils.IS_NODE -> requireCrypto()
else -> windowCrypto()
}
}
private val _crypto: Crypto = js("(globalThis ? globalThis.crypto : (window.crypto || window.msCrypto))")

private external class Crypto {
val subtle: SubtleCrypto

fun getRandomValues(array: Int8Array)

fun randomFillSync(array: Int8Array)
}

private external class SubtleCrypto {
Expand Down