Connect to SOCKS5 Proxy Via PAC script - javascript

In my chrome extension, I am using the PAC script chrome.proxy API that has worked in the past.
How do I connect to a SOCKS5 proxy using this method? I have been using this code, but I get a socks error.
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'mygeoip.co /*')\n" +
" return 'SOCKS5 blackhole:80';\n" +
" return 'SOCKS5 "+ip+":"+port+"';\n" +
"}"
}
};
chrome.proxy.settings.set(
{value: config, scope: 'regular'},
function() {}
);

Related

how to create or write a file in android on phonegap?

I am using below code to write a file on android using PhoneGap, I think that this line window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) { is giving the error, can't find the exact error, just because I can't debug on android.
I find PhoneGap documentation confusing.
function download_file(cur_filename)
{
alert(5);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
alert(2);
console.log('file system open: ' + fs.name);
alert(3);
fs.root.getFile(cur_filename, { create: true, exclusive: false }, function (fileEntry) {
alert("fileEntry is file?" + fileEntry.isFile.toString());
// fileEntry.name == 'someFile.txt'
fileEntry.name==cur_filename;
// fileEntry.fullPath == '/someFile.txt'
writeFile(fileEntry, null);
}, onErrorCreateFile);
}, onErrorLoadFs);
}
function writeFile(fileEntry, dataObj) {
aler(4);
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['some file data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
}
Firstly, you can directly download the file rather than having to create and write a new one. You need to first install the following plugins
cordova plugin add cordova-plugin-file
cordova plugin add cordova-plugin-file-transfer
Now, you need to enclose the below logic inside deviceready event in case you are accessing plugins on app launch. The file-transfer ships with a download() that you need to use for downloading your file. Please find a sample code below
document.addEventListener("deviceready", startDownload, false);
function startDownload() {
var fileTransfer = new FileTransfer();
// replace uri with -> http://192.168.43.54/text.csv
var uri = encodeURI("https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_1920_18MG.mp4");
fileTransfer.download(
uri,
cordova.file.dataDirectory + 'videos/big_buck_bunny_720p_1mb.mp4',
function(entry) {
console.log("download complete: ", entry);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
}
);
}
Once the download is completed, the entry object will have a nativeURL property that holds the local URL to the file.
More info
File Plugin
File-Transfer Download

Microsoft office 365 add-in + Azure Auth token graph

I have a problem getting token for Microsoft Graph.
I have followed this documentation to get the token.
With the Office Javascript API, I get from my add-in the identity token and the application token.
I have put my add-in on the exchange server, I have checked that an application was created in Azure Active Directory, add all authorizations for Microsoft Graph and Azure Active Directory for this application and generate a key for API access.
When I'm in Outlook, I open my add-in and I get the 2 token. In this step, i think the first step is done.
function getCallbackToken() {
Office.context.mailbox.getCallbackTokenAsync(cbToken);
}
function cbToken(asyncResult) {
var token = asyncResult.value;
console.log("token : " + token);
}
function getIdentityToken() {
Office.context.mailbox.getUserIdentityTokenAsync(cbIdentity);
}
function cbIdentity(asyncResult) {
var identity = asyncResult.value;
console.log("identity : " + identity);
}
function getMailUser() {
console.log(
"displayName : " +
Office.context.mailbox.userProfile.displayName +
", mail adresse : " +
Office.context.mailbox.userProfile.emailAddress
);
}
when I send theses token to my java server, I would like to get the token to Microsoft Graph, I request azure with ADAL4J library with this code
//idToken , token identity or token application get from addin api javascript
public AuthenticationResult acquireTokenForGraphApi(String idToken)
throws Throwable {
final ClientCredential credential = new ClientCredential(" --- application id get in azure application list --- ",
" --- generate key from azure application setting, only display one time ---");
final UserAssertion assertion = new UserAssertion(idToken);
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
String tenantId = "--- tocken get in azure configuration panel, application endpoints";
final AuthenticationContext context = new AuthenticationContext(
"https://login.microsoftonline.com/" + tenantId + "/", false, service);
final Future<AuthenticationResult> future = context.acquireToken("https://graph.windows.net/", assertion, credential, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException(
"unable to acquire on-behalf-of token for client " + aadAuthFilterProp.getClientId());
}
return result;
i get an error code
com.microsoft.aad.adal4j.AuthenticationException: {
"error_description": "AADSTS50013: Assertion contains an invalid signature."
[
Reason - The key was not found.,
Thumbprint of key used by client: '0600F9F674620737E73404E287C45A818CB7CEB8',
Configured keys:
[
Key0:Start=02/18/2018, End=02/19/2020, Thumbprint=oZkMJ7Omv9GN7JVM;
Key1:Start=03/31/2018, End=03/31/2020, Thumbprint=xq4mEGikJ5Bkblfw;
Key2:Start=11/16/2016, End=11/16/2018, Thumbprint=i1DVz66b9dfpPV3Z;
]
]
Trace ID: b439ed2f-8a91-401e-91e8-133b57532b00
Correlation ID: cd8ebc72-5173-4725-9c79-e8dc0ef7634b
Timestamp: 2018-04-10 08:27:05Z,
"error": "invalid_grant"
}

Possible to override timeout on js Management SDK Uploads?

I'm trying to upload files that are between 20-100MB in size, but they always fail to upload in under 30 seconds. This is where the timeout is configured, contentful-sdk-core/dist/es-modules/create-http-client.js:
var defaultConfig = {
insecure: false,
retryOnError: true,
logHandler: function logHandler(level, data) {
if (level === 'error' && data) {
var title = [data.name, data.message].filter(function (a) {
return a;
}).join(' - ');
console.error('[error] ' + title);
console.error(data);
return;
}
console.log('[' + level + '] ' + data);
},
// Passed to axios
headers: {},
httpAgent: false,
httpsAgent: false,
timeout: 30000,
proxy: false,
basePath: ''
};
var config = _extends({}, defaultConfig, options);
Can I override these settings to allow for a more generous timeout?
Edit: I have tried changing them directly in the config options, and it works, but I don't think this is a sustainable way of doing things.
I got an answer from Contentful here:
https://www.contentfulcommunity.com/t/large-file-upload-timeout/607/4
Basically, just add a timeout when creating the space, like this:
var contentful = require('contentful')
var client = contentful.createClient({
// This is the space ID. A space is like a project folder in Contentful terms
space: <space-id>,
// This is the access token for this space. Normally you get both ID and the
token in the Contentful web app
accessToken: <delivery-token>,
timeout: 999999
})

AWS SDK can't add Lambda as target to Cloudwatch event

I am developing an application where I need to schedule a task, so I am using AWS Lambda for it.However, the scheduled time is dynamic, since it depends on the user request, it can't be scheduled using AWS Console, so I use AWS Javascript SDK to schedule it.
This is the flow:
Create a CloudWatch Rule (this is successful, I can see the rule being created in the console
Add permission to the policy of lambda, so that cloudwatch event can invoke it (Lambda function code is same for all request, so I created a lambda function in AWS Console instead of using SDK)
Add target to the rule created in Step 1 (this step fails). The error i get is RoleArn is not supported for target arn:aws:lambda:eu-west-1:629429065286:function:prebook.
Below is the Node.js code I wrote
schedule_aws_lambda: function(booking_id, cronTimeIST, callback){
var event = new AWS.CloudWatchEvents({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: 'eu-west-1'
});
var lambda = new AWS.Lambda({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: 'eu-west-1'
});
var year = cronTimeIST.utc().year();
var month = cronTimeIST.utc().month() + 1;
var date = cronTimeIST.utc().date();
var hour = cronTimeIST.utc().hour();
var minute = cronTimeIST.utc().minute();
var cronExpression = "cron(" + minute + " "+ hour + " " + date + " " + month + " ? " + year +")";
var hour_minute = cronTimeIST.format("HH_mm");
var ruleParams = {
Name: 'brodcast_' + booking_id + '_' + hour_minute,
Description: 'prebook brodcast for ' + booking_id + '_' + hour_minute,
ScheduleExpression: cronExpression,
RoleArn: 'arn:aws:iam::629429065286:role/service-role/prebook_lambda_role',
State: 'ENABLED',
};
event.putRule(ruleParams).promise()
.then(data => {
var lambdaPermission = {
FunctionName: 'arn:aws:lambda:eu-west-1:629429065286:function:prebook',
StatementId: 'brodcast_' + booking_id + '_' + hour_minute,
Action: 'lambda:*',
Principal: 'events.amazonaws.com',
};
return lambda.addPermission(lambdaPermission).promise();
})
.then(data => {
var targetParams = {
Rule: ruleParams.Name,
Targets: [
{
Id: 'default',
Arn: 'arn:aws:lambda:eu-west-1:629429065286:function:prebook',
RoleArn: ruleParams.RoleArn,
Input: JSON.stringify({booking_id: booking_id})
}
]
};
return event.putTargets(targetParams).promise();
})
.then(data => {
callback(null, data);
})
.catch(err => {
callback(err)
});
}
I know it has to do something with the Role which doesn't have some permission, I can't figure out the exact cause, I have given the following access for the role
And this is the policy document
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Basically, I want to attach many triggers(the trigger time is not known to me it depends on user request) to the lambda function, however, lambda function code is same for all.
Try removing the RoleArn property. If you are adding permissions to the Lambda function to allow CloudWatch events to invoke it, you don't need it.
In the function policy, make sure you add the SourceArn of the event.
Here's the reference from the docs that explains the error. You must use a resource policy (= Lambda permission), not an identity policy (= role) to invoke Lambda from EventBridge:
Docs: Amazon SQS, Amazon SNS, Lambda, CloudWatch Logs, and EventBridge bus targets do not use roles, and permissions to EventBridge must be granted via a resource policy. API Gateway targets can use either resource policies or IAM roles.
The Lambda AddPermission API creates the resource policy.

Vertx JS Eventbus connection being created then closing

Background: using Vertx 3.3.3 Core and Web on Java side as a server, using vertx-web-3.3.3-client.js as the client with sockjsclient1.1.2.js
Issue: I am successfully making a connection to the eventbus from the client when on my local machine or LAN. When I go through a proxy, the wss eventbus connection is being blocked (in Firefox I see "Firefox can't establish a connection to "wss://..."; in Chromium I see "WebSocket connection to wss://... failed: Error during WebSocket handshake: Unexpected response code: 400", then I see "https ://.../eventbus/.../xhr_send?t=... Failed to load resource: the server responded with a status code of 500"). However, the onopen fires and I receive some data (connection downgraded to an accepted protocol?). Immediately after this, onclose fires and I have lost connection. I know that I am successfully reaching the Java vertx server because my static web and API calls are working.
Questions: I have looked through the Vertx and SockJS documentation extensively. Is there:
Documentation on how vertx tries different transport protocols in the JS Eventbus connection?
An example of JS Vertx Eventbus working through a business proxy?
Another way to implement the Eventbus connection, perhaps specifying the SockJS protocol(s) to try/use? (I am trying the simplest way to create an eventbus connection, as shown in many places in documentation)
Something I need to do on the Java side of the SockJS/Eventbus setup?
Thanks in advance for any advice/help!
EDIT 1: Adding the following code for both Java server and JavaScript web client sides. The web side is very basic (and what is failing). The Java side is using Spring for dependency injection and application config, has an Eventbus connection, one API call, and serves static web content.
The API call from client to server works, and the server sources the web contents correctly, so accessing the tool is working. However, the proxy is causing wss to fail (as expected) but the downgrade to xhr-streaming is failing (I think)
Javascript:
var EB;
var URL;
var APICall = "api/eventbus/publish/";
var IncomingAddress = "heartbeat-test";
var OutgoingAddress = "client-test";
function createConnection(){
URL = $("#serveraddressinput").val(); //Getting url from html text box
console.log("Creating Eventbus connection at " + URL + "eventbus"); //Eventbus address is '<link>/eventbus'
EB = new EventBus(URL + "eventbus");
testAPICall();
EB.onopen = function(){
console.log("Eventbus connection successfully made at " + URL + "eventbus");
console.log("Registering Eventbus handler for messages at " + IncomingAddress);
EB.registerHandler(IncomingAddress, function(error, message){
console.log("Received Eventbus message " + JSON.stringify(message));
};
EB.onclose = function(){
console.log("Eventbus connection at " + URL + " has been lost");
URL = "";
};
}
function testAPICall(){
var link = URL + APICall + "heartbeat-test";
console.log("Testing API call to " + link);
$.ajax({
url: link,
type: 'POST',
data: JSON.stringify({"testFromClient": "Test message sent from Client via API Call"}),
dataType: 'json',
success: function (data, textStatus) {
console.log("API Call Success: " + JSON.stringify(data));
},
error: function (request, error) {
console.log("API Call ERROR: " + JSON.stringify(request) + " " + error);
}
});
}
function sendTestMessage(){
console.log("Sending test message to address " + OutgoingAddress);
EB.send(OutgoingAddress, "Testing 1, 2, 3...");
}
Java:
...
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.JksOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.sockjs.BridgeEvent;
import io.vertx.ext.web.handler.sockjs.BridgeEventType;
import io.vertx.ext.web.handler.sockjs.BridgeOptions;
import io.vertx.ext.web.handler.sockjs.PermittedOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import org.apache.logging.log4j.Level;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
#Service
public class MyTestVerticle extends AbstractVerticle {
private final static Logger log = LoggerFactory.getLogger(MyTestVerticle.class);
final Level ACCESS = Level.forName("ACCESS", 450);
private boolean started;
private int port;
#Value("${webserver.testpath.enabled}")
private boolean testPathEnabled;
#Value("${webserver.urlpath.test}")
private String testUrlPath;
#Value("${webserver.filepath.test}")
private String testFilePath;
#Value("${webserver.caching.enabled}")
private boolean cachingEnabled;
#Value("${webserver.ssl.enabled}")
private boolean sslEnabled;
private BridgeOptions bridgeOptions;
private SockJSHandler sockJsHandler;
private Router router;
private JksOptions sslKeyStoreOptions;
private JksOptions sslTrustStoreOptions;
public MyTestVerticle() {
this.started = false;
}
#Override
public void start(Future<Void> fut) throws Exception {
log.info("start() -- starting Vertx Verticle with eventbus, API handler, and static file handler");
// grab the router
router = getRouter();
// enable CORS for the router
CorsHandler corsHandler = CorsHandler.create("*"); //Wildcard(*) not allowed if allowCredentials is true
corsHandler.allowedMethod(HttpMethod.OPTIONS);
corsHandler.allowedMethod(HttpMethod.GET);
corsHandler.allowedMethod(HttpMethod.POST);
corsHandler.allowedMethod(HttpMethod.PUT);
corsHandler.allowedMethod(HttpMethod.DELETE);
corsHandler.allowCredentials(false);
corsHandler.allowedHeader("Access-Control-Request-Method");
corsHandler.allowedHeader("Access-Control-Allow-Method");
corsHandler.allowedHeader("Access-Control-Allow-Credentials");
corsHandler.allowedHeader("Access-Control-Allow-Origin");
corsHandler.allowedHeader("Access-Control-Allow-Headers");
corsHandler.allowedHeader("Content-Type");
// enable handling of body
router.route().handler(BodyHandler.create());
router.route().handler(corsHandler);
router.route().handler(this::handleAccessLogging);
// publish a payload to provided eventbus destination
router.post("/api/eventbus/publish/:destination").handler(this::publish);
// open up all for outbound and inbound traffic
bridgeOptions = new BridgeOptions();
bridgeOptions.addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"));
bridgeOptions.addInboundPermitted(new PermittedOptions().setAddressRegex(".*"));
// sockJsHandler = SockJSHandler.create(vertx).bridge(bridgeOptions);
sockJsHandler = SockJSHandler.create(vertx);
sockJsHandler.bridge(bridgeOptions, be -> {
try {
if (be.type() == BridgeEventType.SOCKET_CREATED) {
handleSocketOpenEvent(be);
}
else if(be.type() ==BridgeEventType.REGISTER) {
handleRegisterEvent(be);
}
else if(be.type() ==BridgeEventType.UNREGISTER) {
handleUnregisterEvent(be);
}
else if(be.type() ==BridgeEventType.SOCKET_CLOSED) {
handleSocketCloseEvent(be);
}
} catch (Exception e) {
} finally {
be.complete(true);
}
});
router.route("/eventbus/*").handler(sockJsHandler);
if(testPathEnabled){
router.route("/" + testUrlPath + "/*").handler(StaticHandler.create(testFilePath).setCachingEnabled(cachingEnabled));
}
// create periodic task, pushing all current EventBusRegistrations
vertx.setPeriodic(1000, handler -> {
JsonObject obj =new JsonObject();
obj.put("testMessage", "Periodic test message from server...");
vertx.eventBus().publish("heartbeat-test", Json.encodePrettily(obj));
});
EventBus eb = vertx.eventBus();
eb.consumer("client-test", message -> {
log.info("Received message from client: " + Json.encodePrettily(message.body()) + " at " + System.currentTimeMillis());
});
HttpServerOptions httpOptions = new HttpServerOptions();
if(sslEnabled){
httpOptions.setSsl(true);
httpOptions.setKeyStoreOptions(sslKeyStoreOptions);
}
log.info("starting web server on port: " + port);
vertx
.createHttpServer(httpOptions)
.requestHandler(router::accept).listen(
port,
result -> {
if (result.succeeded()) {
setStarted(true);
log.info("Server started and ready to accept requests");
fut.complete();
} else {
setStarted(false);
fut.fail(result.cause());
}
}
);
}
private void handleSocketOpenEvent(BridgeEvent be){
String host =be.socket().remoteAddress().toString();
String localAddress = be.socket().localAddress().toString();
log.info("Socket connection opened! Host: " + host + " Local address: " + localAddress);
}
private void handleRegisterEvent(BridgeEvent be){
String host =be.socket().remoteAddress().toString();
String localAddress = be.socket().localAddress().toString();
String address = be.getRawMessage().getString("address").trim();
log.info("Eventbus register event! Address: " + address + " Host: " + host + " Local address: " + localAddress);
}
private void handleUnregisterEvent(BridgeEvent be){
String host =be.socket().remoteAddress().toString();
String localAddress = be.socket().localAddress().toString();
String address = be.getRawMessage().getString("address").trim();
log.info("Eventbus unregister event! Address: " + address + " Host: " + host + " Local address: " + localAddress);
}
private void handleSocketCloseEvent(BridgeEvent be){
String host =be.socket().remoteAddress().toString();
String localAddress = be.socket().localAddress().toString();
log.info("Socket connection closed! Host: " + host + " Local address: " + localAddress);
}
//Method handles logging at custom level for access logging to files
private void handleAccessLogging(RoutingContext routingContext){
Marker accessMarker = MarkerFactory.getMarker("ACCESS");
if(routingContext.normalisedPath().contains("/api")){
log.info(accessMarker, "Api access log: request= " + routingContext.normalisedPath() + " source=" + routingContext.request().remoteAddress());
}
else{
log.info(accessMarker, "Web access log: path= " + routingContext.normalisedPath() + " source= " + routingContext.request().remoteAddress());
}
routingContext.next();
}
/**
* Accept a payload (anything) and publish to the provided destination
*
* #param routingContext
*/
private void publish(RoutingContext routingContext) {
String destination = routingContext.request().getParam("destination");
String payload = routingContext.getBodyAsString();
if ((destination == null) || (payload == null)) {
Exception e = new Exception("Missing arguments");
routingContext.response().setStatusCode(406);
routingContext.fail(e);
} else {
log.info("API Call -> Publishing to destination: " + destination + " payload: " + payload);
vertx.eventBus().publish(destination, payload);
routingContext
.response()
.setStatusCode(200)
.putHeader("content-type", "application/json; charset=utf-8")
.end(payload);
}
}
public boolean isStarted() {
return started;
}
public void setStarted(boolean started) {
this.started = started;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public Router getRouter(){
if(router == null){
router = Router.router(vertx);
}
return router;
}
public void setRouter(Router router){
this.router = router;
}
public void setSslOptions(JksOptions keyStoreOptions, JksOptions trustStoreOptions) {
this.sslKeyStoreOptions = keyStoreOptions;
this.sslTrustStoreOptions = trustStoreOptions;
}
}
This error can be resolved by doing the following:
In the Java verticle, move the Eventbus handler to the top, before any other handlers. I believe the BodyHandler or CorsHandler were messing it up and causing the 500 error.
...
router.route("/eventbus/*").handler(sockJsHandler);
...
// enable handling of body
router.route().handler(BodyHandler.create());
router.route().handler(corsHandler);
router.route().handler(this::handleAccessLogging);
// publish a payload to provided eventbus destination
router.post("/api/eventbus/publish/:destination").handler(this::publish);

Categories

Resources