Proper Security when evaluating Javascript from within Swift code using callAsyncJavaScript

I am currently using the WKWebView to evaluate Javascript in my Swift code. This code uses the callAsyncJavaScript to evaluate Javascript. My code takes parameters from the user and then injects those parameters into the Javascript string that is evaluated by callAsyncJavaScript.

This of course is an opportunity for js injection attacks that could cause unwanted js to run. I know Apple uses WebViews in their own native apps like Music. But there is nowhere I can find best practices on how to prevent js injection attacks.

Anyone have experience with this? Here's a sample function I use.

func createMessage(message: ARMessageDto) async -> ArweaveResult {
    do {
      guard self.walletStr != nil && !self.walletStr!.isEmpty else {
        return Result.failure(TransactionError.General("No wallet exists for this user"))
      }
      let balance = try await self.arweaveQuerySvc.getBalance()
      if balance < 1_000_000_000_000 {
        return Result.failure(TransactionError.General("Error wallet balance is less than 1,000,000,000,000 Winston"))
      }
      guard case .none = message.validate() else {
        return Result.failure(TransactionError.ParametersInvalid(message.validate()))
      }
       
      let respondingToTransId = message.respondingToTransId ?? ""
      let result = try await self.webView!.callAsyncJavaScript("""
            \(baseScript!)
            const arweaveSvc = main('\(walletStr!)');
            const result = await arweaveSvc.createMessage(
              '\(message.msg)',
              \"\(message.userName)\",
              \"\(respondingToTransId)\"
            );
            return result;
          """, contentWorld: WKContentWorld.defaultClient)
      _ = await self.arweaveQuerySvc.mine()
      return try getTransactionResult(result: result)
    } catch {
      return Result.failure(TransactionError.General("Failed to create profile"))
    }
  }

use the callAsyncJavaScript "arguments" parameter

1 Like