PhantomJS Version 1.9.1 - Issues with Proxy Authentication - authentication

Can someone please help me out on this?
I have spent a considerable amount of time setting up PhantomJS to save JPGs of specific web-pages and it works/ed really well until I went to deploy it on a machine which accesses the net through a proxy.
Now, whatever I try, I can not get the authentication right?
Has anyone EVER managed to do this?
I am using command line arguments:
--proxy=xx.xx.xx.xx:8080
--proxy-type=http
--proxyAuth=myusername:mypassword
I have checked on the Proxy (TMG) which still insists that my username is anonymous rather than the one which I am sending through using the command line.
From the --debug, I am able to see that proxy, proxyType and proxyAuth have all been populated correctly so PhantomJS is understanding the command line, yet when it runs, it still returns 'Proxy requires authentication'
Where am I going wrong?
Thanks for reading this and, hopefully, helping me out
BTW - I am using Windows 7 - 64 bit

OK, so I've done a whole load of digging on this and have got it working. So I thought I would publish what I found in case it might help someone else.
One of the things that I found when I was searching around is that there was a bit of a discussion about the inclusion of the following in the headers which are submitted by the JS which is used to drive PhantomJS:
page.customHeaders={'Authorization': 'Basic '+btoa('username:password')};
rather than using
page.settings.userName = 'username';
page.settings.password = 'password';
which will not work. Please refer to Previous Discussion
This is fine if you are using basic levels of authentication on the proxy. It will not work if you are using Integrated Authetication as this will still require NTLM/Kerberos or whatever.
The way around this is to change the settings on the client.
You need to allow the client access to the outside world WITHOUT it routing through the proxy. Certainly in TMG, this is done by changing the settings which apply to the Client Network Software which is installed on the client hardware.
By allowing the PhantomJS Executable to bypass the proxy, you will overcome the problems which I and many others have experienced but you will still have a bit of an issue as you will have just broken your system security so be aware and hope that there is a new version PhantomJS which handles NTLM/Kerberos.
Alternatively, change your Proxy to use Basic Authentication which will allow the use to the customHeaders solution to work as above but this is potentially an even greater risk to you security than allowing the client to bypass the proxyy.

var page = require('webpage').create(),
system = require('system'),
fs = require('fs'),
fileName = 'phantomjs',
extension = 'log',
file = fs.open(fileName + '.' + extension, 'w'),
address,
output,
delay,
version = phantom.version.major + '.'
+ phantom.version.minor + '.'
+ phantom.version.patch ;
if (system.args.length === 1){
console.log('Usage: example.js <some URL> delay');
phantom.exit();
}
// Handle the command line arguments
address = system.args[1];
output = system.args[2];
delay = system.args[3];
// Write the Headers into the log file
file.writeLine("PhantomJS version: " + version);
file.writeLine("Opening page: " + address);
file.writeLine("Writing image to: " + output);
file.writeLine("Applying a delay of: " + delay + " milliseconds");
function quit(reason, value) {
console.log("Quit: " + reason);
file.writeLine("Quit: " + reason);
file.close();
if (value !== 1){
// If there has been an error reported, stick a datetime stamp on the log to retain it
var d = new Date();
var dateString = d.getFullYear().toString() +
((d.getMonth() + 1) <= 9 ? '0' : '') + (d.getMonth() + 1).toString() +
(d.getDate() <= 9 ? '0' : '') + d.getDate().toString() +
(d.getHours() <= 9 ? '0' : '') + d.getHours().toString() +
(d.getMinutes() <= 9 ? '0' : '') + d.getMinutes().toString() +
(d.getSeconds() <= 9 ? '0' : '') + d.getSeconds().toString();
fs.move(fileName + '.' + extension, fileName + '_' + dateString + '.' + extension);
}
phantom.exit(value);
}
page.onResourceError = function(resourceError) {
page.reason = resourceError.errorString;
page.reason_url = resourceError.url;
};
page.onError = function (msg, trace) {
console.log(msg);
file.writeLine(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
//file.writeLine(' ', item.file, ':', item.line);
})
quit("Failed", 0);
}
page.onResourceRequested = function (request) {
file.writeLine('Request: ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function (response) {
file.writeLine('Receive: ' + JSON.stringify(response, undefined, 4));
};
// Set a user agent - if required
//page.settings.userAgent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; .NET CLR 1.1.4322)';
// And open the page
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address: \"' + page.reason_url + '\": ' + page.reason);
file.writeLine('Unable to load the address: \"' + page.reason_url + '\": ' + page.reason);
quit("Failed", 0);
}
else {
window.setTimeout(function() {
console.log('Saving the page!');
file.writeLine('Saving the page!');
page.render(output);
quit("Finished", 1);
}, delay);
}
});

Related

codename one push notification meet error "javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure"

We have a web project which is always working fine, it just using codename one push api to push notification to our devices, but it suddenly get the following error:
javax.net.ssl.SSLHandshakeException: Received fatal alert:
handshake_failure
Below is the core code (same with codenamoe one demo)
HttpURLConnection connection = (HttpURLConnection)new URL("https://push.codenameone.com/push/push").openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
String cert = ITUNES_DEVELOPMENT_PUSH_CERT;
String pass = ITUNES_DEVELOPMENT_PUSH_CERT_PASSWORD;
if(ITUNES_PRODUCTION_PUSH) {
cert = ITUNES_PRODUCTION_PUSH_CERT;
pass = ITUNES_PRODUCTION_PUSH_CERT_PASSWORD;
}
String query = "token=" + PUSH_TOKEN +
"&device=" + URLEncoder.encode(deviceId1, "UTF-8") +
"&device=" + URLEncoder.encode(deviceId2, "UTF-8") +
"&device=" + URLEncoder.encode(deviceId3, "UTF-8") +
"&type=1" +
"&auth=" + URLEncoder.encode(FCM_SERVER_API_KEY, "UTF-8") +
"&certPassword=" + URLEncoder.encode(pass, "UTF-8") +
"&cert=" + URLEncoder.encode(cert, "UTF-8") +
"&body=" + URLEncoder.encode(MESSAGE_BODY, "UTF-8") +
"&production=" + ITUNES_PRODUCTION_PUSH +
"&sid=" + URLEncoder.encode(WNS_SID, "UTF-8") +
"&client_secret=" + URLEncoder.encode(WNS_CLIENT_SECRET, "UTF-8");
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes("UTF-8"));
}
int c = connection.getResponseCode();
// read response JSON
I directly run the code in unit test, it works well.
But when I call the function from project (such as a button from webpage), the error happened.
I tried several way to solve it but still can not work, please give me some suggestion to fix the issue. Thank you!
This generally happens if the certificate is invalid or out of date etc. It can happen if your connection. I just verified our SSL certificate on the push servers and it's valid (generated by cloudflare) so I suggest checking the routes to the server and your version of Java. You should have Java 8 or newer with a recent enough minor update version.

Incoming Express parameters are not the same as whats passed in

I have a strange issue where I have passed in parameters from a URL, into my Express server,
When I get the req.params.code & req.params.mode variables, they are different than what is passed in through the URL.
Allow me to show you...
Here is the Express code:
router.get('/verify/:user/:mode/:code', function(req,res){
console.log("STARTING VERIFICATION");
var code = req.params.code;
console.log('code: ' + code);
var user = req.params.user;
console.log('user: ' + user);
var mode = req.params.mode;
console.log('mode: ' + mode);
console.log('req.params: ' + JSON.stringify(req.params));
var regex = new RegExp(["^", req.params.user, "$"].join(""), "i");
console.log('REGEX: ' + regex);
var verified = false;
console.log('req.params: ' + req.params);
console.log('req.body: ' + req.body);
console.log("rx: "+ regex);
console.log('req.params.code: ' + req.params.code);
console.log('req.params.user: ' + req.params.user);
etc... etc... etc...
Here is the output in the console:
STARTING VERIFICATION
code: background-cycler.js
user: admin
mode: js
req.params: {"user":"admin","mode":"js","code":"background-cycler.js"}
REGEX: /^admin$/i
req.params: [object Object]
req.body: [object Object]
rx: /^admin$/i
req.params.code: background-cycler.js
req.params.user: admin
Here is the URL that is passed into the browser:
https://examplesite.com/verify/admin/sms/9484
I want to say that this code worked prior to dusting it off and moving an instance to google's cloud compute...
As you can see, the parameters passed in to the verify, code should be 9484 and mode should be sms. Instead i'm getting an unintended js filename, and a js mode instead.
UPDATE: As requested I added this within the Express route function:
console.log(req.originalUrl);
and I get this result:
/verify/admin/js/background-cycler.js
I can verify the URL that sent this was:
https://examplesite.com/verify/admin/sms/9484

Multipart form upload of binary file using casperjs outside of state machine (can't use fill)

UPDATE 1: I've created a GIST with actual running code in a test jig to show exactly what I'm running up against. I've included working bot tokens (to a throw-away bot) and access to a telegram chat that the bot is already in, in case anyone wants to take a quick peek. It's
https://gist.github.com/pleasantone/59efe5f9d7f0bf1259afa0c1ae5a05fe
UPDATE 2: I've looked at the following articles for answers already (and a ton more):
https://github.com/francois2metz/html5-formdata/blob/master/formdata.js
PhantomJS - Upload a file without submitting a form
https://groups.google.com/forum/#!topic/casperjs/CHq3ZndjV0k
How to instantiate a File object in JavaScript?
How to create a File object from binary data in JavaScript
I've got a program written in casperjs (phantomjs) that successfully sends messages to Telegram via the BOT API, but I'm pulling my hair out trying to figure out how to send up a photo.
I can access my photo either as a file, off the local filesystem, or I've already got it as a base64 encoded string (it's a casper screen capture).
I know my photo is good, because I can post it via CURL using:
curl -X POST "https://api.telegram.org/bot<token>/sendPhoto" -F chat_id=<id> -F photo=#/tmp/photo.png
I know my code for connecting to the bot api from within capserjs is working, as I can do a sendMessage, just not a sendPhoto.
function sendMultipartResponse(url, params) {
var boundary = '-------------------' + Math.floor(Math.random() * Math.pow(10, 8));
var content = [];
for (var index in params) {
content.push('--' + boundary + '\r\n');
var mimeHeader = 'Content-Disposition: form-data; name="' + index + '";';
if (params[index].filename)
mimeHeader += ' filename="' + params[index].filename + '";';
content.push(mimeHeader + '\r\n');
if (params[index].type)
content.push('Content-Type: ' + params[index].type + '\r\n');
var data = params[index].content || params[index];
// if (data.length !== undefined)
// content.push('Content-Length: ' + data.length + '\r\n');
content.push('' + '\r\n');
content.push(data + '\r\n');
};
content.push('--' + boundary + '--' + '\r\n');
utils.dump(content);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
if (true) {
/*
* Heck, try making the whole thing a Blob to avoid string conversions
*/
body = new Blob(content, {type: "multipart/form-data; boundary=" + boundary});
utils.dump(body);
} else {
/*
* this didn't work either, but both work perfectly for sendMessage
*/
body = content.join('');
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// xhr.setRequestHeader("Content-Length", body.length);
}
xhr.send(body);
casper.log(xhr.responseText, 'error');
};
Again, this is in a CASPERJS environment, not a nodejs environment, so I don't have things like fs.createReadableStream or the File() constructor.

Google API for getting maximum number of licenses in a Google Apps domain

I have a Google Apps Script function used for setting up accounts for new employees in our Google Apps domain.
The first thing it does is makes calls to the Google Admin Settings API and retrieves the currentNumberOfUsers and maximumNumberOfUsers, so it can see if there are available seats (otherwise a subsequent step where the user is created using the Admin SDK Directory API would fail).
It's been working fine until recently when our domain had to migrate from Postini to Google Vault for email archiving.
Before the migration, when creating a Google Apps user using the Admin SDK Directory API, it would increment the currentNumberOfUsers by 1 and the new user account user would automatically have access to all Google Apps services.
Now after the migration, when creating a Google Apps user, they aren't automatically assigned a "license," so I modified my script to use the Enterprise License Manager API and now it assigns a "Google-Apps-For-Business" license. That works fine.
However, the currentNumberOfUsers is now different from the number of assigned licenses, and "Google-Apps-For-Business" is only one of several different types of licenses available.
I can get the current number of assigned "Google-Apps-For-Business" licenses by running this:
var currentXml = AdminLicenseManager.LicenseAssignments.listForProductAndSku('Google-Apps', 'Google-Apps-For-Business', 'domain.com', {maxResults: 1000});
var current = currentXml.items.toString().match(/\/sku\/Google-Apps-For-Business\/user\//g).length;
But the number that produces is different from currentNumberOfUsers.
All I really need to do now is get the maximum number of owned "Google-Apps-For-Business" licenses so the new employee setup script can determine whether there are any available.
I checked the API Reference documentation for the following APIs but...
Enterprise License Manager API → Doesn't have a method for getting the maximum or available number of licenses.
Google Admin Settings API → Doesn't deal with licenses, only "users."
Admin SDK Directory API User resource → Doesn't deal with licenses.
Google Apps Reseller API → This API seems to have what I need, but it's only for Reseller accounts.
I know I can program my new employee setup script to just have a try/catch seeing if it would be able to create the user and assign the license, and end the script execution gracefully if it can't, but that doesn't seem efficient.
Also, part of the old script was that if there were less than X seats available, it would email me a heads-up to order more. I can program a loop that attempts to repeatedly create dummy users and assign them licenses and count the number of times it can do that before it fails, then delete all the dummy users, but, once again, that's not efficient at all.
Any ideas?
Update 3/11/2020: Since the Admin Settings API had shut down a few years ago I've been using the Enterprise License Manager API to get the current number of used licenses, like this:
function getCurrentNumberOfUsedGoogleLicenses(skuId) {
var success = false, error = null, count = 0;
var adminEmail = 'admin#domain.com';
var gSuiteDomain = adminEmail.split('#')[1];
// for more information on the domain-wide delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
// the getDomainWideDelegationService() function uses this:
// https://github.com/gsuitedevs/apps-script-oauth2
var service = getDomainWideDelegationService('EnterpriseLicenseManager: ', 'https://www.googleapis.com/auth/apps.licensing', adminEmail);
if (skuId == 'Google-Apps-Unlimited') var productId = 'Google-Apps';
else return { success: success, error: "Unsupported skuId", count: count };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.method = "GET";
requestBody.muteHttpExceptions = false;
var data, pageToken, pageTokenString;
var maxAttempts = 5;
var currentAttempts = 0;
var pauseBetweenAttemptsSeconds = 3;
loopThroughPages:
do {
if (typeof pageToken === 'undefined') pageTokenString = "";
else pageTokenString = "&pageToken=" + encodeURIComponent(pageToken);
var url = 'https://www.googleapis.com/apps/licensing/v1/product/' + productId + '/sku/' + skuId + '/users?maxResults=1000&customerId=' + gSuiteDomain + pageTokenString;
try {
currentAttempts++;
var response = UrlFetchApp.fetch(url, requestBody);
var result = JSON.parse(response.getContentText());
if (result.items) {
var licenseAssignments = result.items;
var licenseAssignmentsString = '';
for (var i = 0; i < licenseAssignments.length; i++) {
licenseAssignmentsString += JSON.stringify(licenseAssignments[i]);
}
if (skuId == 'Google-Apps-Unlimited') count += licenseAssignmentsString.match(/\/sku\/Google-Apps-Unlimited\/user\//g).length;
currentAttempts = 0; // reset currentAttempts before the next page
}
} catch(e) {
error = "Error: " + e.message;
if (currentAttempts >= maxAttempts) {
error = 'Exceeded ' + maxAttempts + ' attempts to get license count: ' + error;
break loopThroughPages;
}
} // end of try catch
if (result) pageToken = result.nextPageToken;
} while (pageToken);
if (!error) success = true;
return { success: success, error: error, count: count };
}
However, there still does not appear to be a way to get the maximum number available to the domain using this API.
Use CustomerUsageReports.
jay0lee is kind enough to provide the GAM source code in Python. I crudely modified the doGetCustomerInfo() function into Apps Script thusly:
function getNumberOfLicenses() {
var tryDate = new Date();
var dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
while (true) {
try {
var response = AdminReports.CustomerUsageReports.get(dateString,{parameters : "accounts:gsuite_basic_total_licenses,accounts:gsuite_basic_used_licenses"});
break;
} catch(e) {
//Logger.log(e.warnings.toString());
tryDate.setDate(tryDate.getDate()-1);
dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
continue;
}
};
var availLicenseCount = response.usageReports[0].parameters[0].intValue;
var usedLicenseCount = response.usageReports[0].parameters[1].intValue;
Logger.log("Available licenses:" + availLicenseCount.toString());
Logger.log("Used licenses:" + usedLicenseCount.toString());
return availLicenseCount;
}
I would recommend exploring GAM which is a tool that gives command line access to the administration functions of your domain.

SharePoint 2010 Wiki Template Script Issue

I'm looking for a way to give my SharePoint users a way to create new wiki pages from an existing template. In the process of researching I found a great walkthrough that seems to fit the need (http://www.mssharepointtips.com/tip.asp?id=1072&page=2), but I'm having trouble getting it to work. The problem seems to lie in the assignment of a path to PATHTOWIKI-- if I use "/Weekly Update Wiki", the script returns an error of "There is no Web named '/Weekly Update Wiki'." If I use "Weekly Update Wiki" without the forward slash, I instead get an error of "There is no Web named '/sites/[parentSite]/[childSite]/Weekly Update Wiki/Weekly Update Wiki'."
Any ideas about what I'm not understanding here?
function myCreateProject() {
// Configure these for your environment
// include no slashes in paths
var PATHTOWIKI = "Weekly Update Wiki";
var PATHTOPAGES = "Pages";
// file name only for template page, no extension
var TEMPLATEFILENAME = "Template";
var myPathToWiki = encodeURIComponent(PATHTOWIKI);
var myPathToPages = PATHTOPAGES + "%2f";
var myTemplateFileName = encodeURIComponent(TEMPLATEFILENAME) + "%2easpx";
var EnteredProject = document.getElementById("NewProjName");
var myNewName = EnteredProject.value;
if(myNewName == "") {
alert('Please enter a name for the new project page');
} else {
myNewName = encodeURIComponent(myNewName) + "%2easpx"
$.ajax({
url: PATHTOWIKI + "/_vti_bin/_vti_aut/author.dll",
data: ( "method=move+document%3a14%2e0%2e0%2e4730&service%5fname="
+ myPathToWiki +
"&oldUrl=" + myPathToPages + myTemplateFileName +
"&newUrl=" + myPathToPages + myNewName +
"&url%5flist=%5b%5d&rename%5foption=nochangeall&put%5foption=edit&docopy=true"
),
success: function(data) {
var rpcmsg1 = getMessage(data, "message=", "<p>");
$("#myInfo").append("<br />" + rpcmsg1);
if(rpcmsg1.indexOf("successfully") < 0) {
// get error info
var rpcmsg2 = getMessage(data, "msg=", "<li>");
$("#myInfo").append("<br />" + rpcmsg2 + "<br />");
} else {
$("#myInfo").append("<br />Go to new page<br />");
}
},
type: "POST",
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("X-Vermeer-Content-Type",
"application/x-www-form-urlencoded");
}
});
}
}
Update: I figured out what needed to happen in my case. Since I couldn't get a grasp on the relative approach, I just went with the absolute path for PATHTOWIKI and slightly modified the append in the ajax call.
PATHTOWIKI:
var PATHTOWIKI = "https://[domain]/sites/[parentSite]/[childSite]";
append:
$("#myInfo").append("<br />Go to new page<br />");
The change in the latter line of code is subtle; since I used an absolute path in PATHTOWIKI, I just removed the leading forward slash in the anchor tag, so that <a href=\"/" became <a href=\"". This renders the script slightly less portable, but since it's a one-off effort I'll stick with this unless anything comes along to expand the scope.