Hsts firefox addon - javascript

i 'm writing a firefox addon! i would like to know if the website use hsts, so i call the function isSecureURI() from https://dxr.mozilla.org/comm-central/source/mozilla/security/manager/ssl/nsISiteSecurityService.idl but,always, when i check it return as result false!
here is my code
var activeBrowserWindow = require("sdk/window/utils").getMostRecentBrowserWindow();
Cu.import("resource://gre/modules/Services.jsm");
var gSSService = Cc["#mozilla.org/ssservice;1"]
.getService(Ci.nsISiteSecurityService);
// For now, STS data gets stored in permissions.sqlite.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=775370.
var permissionManager = Cc["#mozilla.org/permissionmanager;1"]
.getService(Ci.nsIPermissionManager);
// We should not store anything permanent in permissions.sqlite in private
// browsing mode.
var FLAGS = require("sdk/private-browsing").isPrivate(activeBrowserWindow) ?
Ci.nsISocketProvider.NO_PERMANENT_STORAGE : 0;
var STS_TYPE = Ci.nsISiteSecurityService.HEADER_HSTS;
var tabs = require("sdk/tabs");
tabs.on('ready', function(tab) {
var URL = tab.url;
var url = require("sdk/url").URL(URL);
var hostname = url.hostname;
//console.log(hostname);
function isSecureUri(hostname) {
var uri = Services.io.newURI("https://" + hostname, null, null);
var resultURI = gSSService.isSecureURI(STS_TYPE, uri, FLAGS);
return resultURI;
}
thank you very much for your time!
ps sorry for my english!

Related

searchParams.get returning "Null" when values are present

I'm trying to grab URL params from a page link to prepopulate a form in an iFrame, but am struggling with the params returning 'null' and need some guidance. So far, the script appears to work by populating the form with "null", however, it is unsuccessfully populating params that have valid values in my URL. The javascript below 'f.src' is scripting provided by my forms service.
(I apologize for the ugly console.logs, but am using those for troubleshooting.)
[Console Preview][1]
***UPDATE: With my updated code, per user suggestion, I updated my .get statements to specify the param with a string, but it's still returning 'null'.
try{
var endpoint = "https://forms.myformsite.com/";
console.log(endpoint);
var url_string = "https://my.site.com/landingpage?fname=Jeff&lname=Bezos&email=jeff#amazon.com&company=Amazon&title=Founder"; /*window.location.href;*/
console.log(url_string);
var url = new URL(url_string);
console.log(url_string);
var fname = url.searchParams.get('fname');
console.log(fname);
var lname = url.searchParams.get('lname');
console.log(lname);
var email = url.searchParams.get('email');
console.log(email);
var company = url.searchParams.get('company');
console.log(company);
var title = url.searchParams.get('title');
console.log(title);
var formURL = endpoint+"&fname="+fname+"&lname="+lname+"&email="+email+"&company"+company+"&title="+title;
console.log(formURL);
var f = document.createElement("iframe");
f.src = formURL;
console.log(f.src);
f.style.border = "none";
f.style.height = "878px";
f.style.width = "90%";
f.style.transition = "all 0.5s ease";
var d = document.getElementById("divFormID");
d.appendChild(f);
window.addEventListener('message', function() {
var evntData = event.data;
if (evntData && evntData.constructor == String) {
var zf_ifrm_data = evntData.split("|");
if (zf_ifrm_data.length == 2) {
var zf_perma = zf_ifrm_data[0];
var zf_ifrm_ht_nw = (parseInt(zf_ifrm_data[2], 10) + 15) + "px";
var iframe = document.getElementById("divFormID").getElementsByTagName("iframe")[0];
if ((iframe.src).indexOf('formperma') > 0 && (iframe.src).indexOf(zf_perma) > 0) {
var prevIframeHeight = iframe.style.height;
if (prevIframeHeight != zf_ifrm_ht_nw) {
iframe.style.height = zf_ifrm_ht_nw;
}
}
}
}
}, false);
} catch (e) {}
})();```
[1]: https://i.stack.imgur.com/z75q0.png
[2]: https://i.stack.imgur.com/bjqoP.png
For all .get() calls, you're passing in an (undefined) variable instead of a string:
var fname = url.searchParams.get(fname);
This should be:
var fname = url.searchParams.get('fname');

Issues with storing and retrieving data from Google Sheets cache

I wrote a function to retrieve Yahoo! Finance data for certain stocks. The sheet was, however, generating too many URL calls to Yahoo! and I was regularly restricted for the rest of the day.
Since the data that I am retrieving is not expected to change often anyway, the solution seems to be using Google Sheets cache to store any values that are retrieved for 7 days before querying live again.
The code is as follows, and a link to the spreadsheet I'm using is below:
function yahoofinance(ticker)
{
var url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(ticker) + '?modules=price,assetProfile,summaryDetail';
var cache = CacheService.getDocumentCache();
var cached = cache.get(url);
if (cached != null)
{
var object = cached;
var source = 'cache';
}
else
{
var response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
var responseCode = response.getResponseCode();
if (responseCode === 200)
{
var object = JSON.parse(response.getContentText());
var source = 'live';
cache.put(url, "cached", 21600);
properties.setProperty(url, object);
}
}
var fwdPE = object.quoteSummary.result[0]?.summaryDetail?.forwardPE?.fmt || '-';
var sector = object.quoteSummary.result[0]?.assetProfile?.sector || '-';
var mktCap = object.quoteSummary.result[0]?.price?.marketCap?.fmt || '-';
return [[source, fwdPE, sector, mktCap]];
}
Link to the Google Sheet
The problem is that any function call gets the same error:
Error
TypeError: Cannot read property 'result' of undefined (line 28).
Line 28 is:
var fwdPE = object.quoteSummary.result[0]?.summaryDetail?.forwardPE?.fmt || '-';
As far as I understand, object (and thus result[]) should be available.
What am I doing wrong. Why is this error generated?
Am Implementing Google cache correctly? What do I need to improve?
Any help is greatly appreciated!
Try it this way
function yahoofinance(ticker) {
const url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/' + encodeURI(ticker) + '?modules=price,assetProfile,summaryDetail';
const cache = CacheService.getDocumentCache();
const cached = cache.get("response");
let object = {};
if (cached) {
object.response = cached;
object.source = 'cache';
} else {
let response = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
if (response.getResponseCode() == 200) {
object.response = JSON.parse(response.getContentText());
object.source = 'live';
cache.put("response", cached, 21600);
}
}
let fwdPE = object.response.quoteSummary.result[0]?.summaryDetail?.forwardPE?.fmt || '-';
let sector = object.response.quoteSummary.result[0]?.assetProfile?.sector || '-';
let mktCap = object.response.quoteSummary.result[0]?.price?.marketCap?.fmt || '-';
return [[object.source, fwdPE, sector, mktCap]];
}

Functions Rerunning in GAS

I'm using GAS to send and receive texts. There is one function that send texts (sendTexts.gs) and one that receives (receiveTexts.gs). I have both of these functions linked to individual buttons on the sheet, but when I run one function, both are running (texts get sent every time). Is there a cache or something that needs to be cleared? The receiveTexts has no commands in the code that could send messages in it, and based on logger testing, I know that both are running when I only click one.
EDIT: This also occurs in the GAS "terminal". If I click run in the script editor both run.
Here is the code with personal/individual info (codes/phone numbers edited out):
function sendSms(to, body) {
var playerArray = getMeta();
Logger.log(playerArray);
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/EDIT/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : "EDIT"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("EDIT")
};
UrlFetchApp.fetch(messages_url, options);
}
function sendAll() {
var spreadsheet = SpreadsheetApp.getActive();
var text = SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName('Meta')).getRange('B4').getValue();
var playerArray = getMeta();
Logger.log(text);
for (i=0; i<playerArray.length;i++) {
try {
var number = playerArray[i][1];
Logger.log(number);
response_data = sendSms(number, text);
status = "sent";
} catch(err) {
Logger.log(err);
status = "error";
}
Logger.log(status);
}
}
function sendTexts() {
sendAll();
}
Logger.log("ran send texts");
Here is the receive texts code with the same adjustments:
function receiveTexts() {
var spreadsheet = SpreadsheetApp.getActive();
var ACCOUNT_SID = "EDIT";
var ACCOUNT_TOKEN = "EDIT";
var toPhoneNumber = "+EDIT";
var sheet = spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Meta'), true);
var playerArray = getMeta();
var numberToRetrieve = playerArray.length;
var hoursOffset = 0;
var options = {
"method" : "get"
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ":" + ACCOUNT_TOKEN)
};
var url="https://api.twilio.com/2010-04-01/Accounts/" + ACCOUNT_SID + "/Messages.json?To=" + toPhoneNumber + "&PageSize=" + numberToRetrieve;
var response = UrlFetchApp.fetch(url,options);
// -------------------------------------------
// Parse the JSON data and put it into the spreadsheet's active page.
// Documentation: https://www.twilio.com/docs/api/rest/response
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Meta'), true);
var numRounds = spreadsheet.getRange('B2').getValue();
var theSheet = SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName('Attacks'),true);
var theColumn = (numRounds*2)+1;
var dataAll = JSON.parse(response.getContentText());
for (i=0; i<dataAll.messages.length; i++){
var sentNumber = dataAll.messages[i].from;
Logger.log(sentNumber);
for (k=0; k<playerArray.length;k++){
Logger.log(playerArray[k][1]);
if (playerArray[k][1]==sentNumber){
var player = k;
Logger.log('Success');
Logger.log(player);
break;
}
}
var playerRow = playerArray[player][0];
Logger.log(playerRow);
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Attacks'),true);
theSheet.getRange(playerRow, theColumn).setValue(dataAll.messages[i].body);
}
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Meta'), true);
sheet.getRange(2,2).setValue(numRounds +1);
}
Logger.log("texts received ran");
EDIT2: I separated out getMeta into a separate file. Now when I run getMeta, it also runs the other two scripts. Anytime any one script is run, all three run. This makes me think it's not related to the code, but related to some setting or something. Does the order of the scripts in the sidebar matter? I feel like that's not it because running any of the three causes all three to be run.

WebCL doesn't fill global table

I started using Nokia WebCL implementation for Mozilla Firefox.
I'm testing my application on Firefox version 32.0 (which is version for which Nokia binding was implemented).
This is my code (for simplicity and to show you what my issue is I've simplified the kernel code to minimum):
Kernel code:
<script id="julia_set" type="text/x-opencl">
__kernel void julia_set(__global int* pix)
{
pix[0]=5;
}
</script>
My Javascript code:
function loadKernel(id){
var kernelElement = document.getElementById(id);
var kernelSource = kernelElement.text;
if (kernelElement.src != "") {
var mHttpReq = new XMLHttpRequest();
mHttpReq.open("GET", kernelElement.src, false);
mHttpReq.send(null);
kernelSource = mHttpReq.responseText;
}
return kernelSource;
}
var platforms = webcl.getPlatforms();
var width = 2;
var height = 2;
var ctx = webcl.createContext(platforms[2],WebCL.DEVICE_TYPE_GPU);
var length = 4*width*height;
var bufSize = 4*length;
var bufferC = ctx.createBuffer (WebCL.MEM_WRITE_ONLY, bufSize);
var kernelSrc = loadKernel("julia_set");
var program = ctx.createProgram(kernelSrc);
var device = ctx.getInfo(WebCL.CONTEXT_DEVICES)[0];
try {
program.build ([device], "");
} catch(e) {
alert ("Failed to build WebCL program. Error "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_STATUS)
+ ": "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_LOG));
throw e;
}
var kernel = program.createKernel ("julia_set");
kernel.setArg (0, bufferC);
var cmdQueue = ctx.createCommandQueue (device);
var local = [16,16];
var global = [32,32];
cmdQueue.enqueueNDRangeKernel(kernel, 2, null,global, local);
var outBuffer = new Uint32Array(length);
cmdQueue.enqueueReadBuffer (bufferC, false, 0, bufSize, outBuffer);
cmdQueue.finish ();
console.log(outBuffer);
It's the most simple OpenCL application I could imagine. I expect my outBuffer to be filled with 0's and first element to be 5, but all the elements are 0. Whatever I try to do in kernel, my array seems untouched.
The device I'm using is NVidia GeForce GT 750M.
What can be possibly wrong in my code?
if(get_global_id(0)==0 && get_global_id(1)==0)
pix[0]=5;
should fix the issue, without race condition.

Detect lock screen or running screensaver with Firefox/OS X

I'm creating an extension for Firefox (SDK Add-on) in which I'll need to detect screensaver and lock-screen events so that I can set a user's availability status in a web-app.
I've managed to do this already for Windows and now need to port to OS X. For the Windows version, I was using calls to native API to find out if screen was locked, etc. Is there a similar way of getting OS information from a Firefox extension on OS X? I've tried Googling this and haven't found a solid answer - any help appreciated!
On OSX you can query a locked screen/screensaver using CGSessionCopyCurrentDictionary and looking for the presence and value of the "CGSSessionScreenIsLocked" key.
This is platform API, so one will have to use js-ctypes again and write a bunch of code to get that working.
I did get it working: The following code is a working example you can run in a privileged Scratchpad. To get a privileged one, open a pad for e.g. about:newtab.
Components.utils.import("resource://gre/modules/ctypes.jsm");
var CoreFoundation = new (function() {
this.CFNumberRef = ctypes.voidptr_t;
this.CFStringRef = ctypes.voidptr_t;
this.CFDictionaryRef = ctypes.voidptr_t;
var lib = ctypes.open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation");
this.CFRelease = lib.declare(
"CFRelease",
ctypes.default_abi,
ctypes.void_t,
ctypes.voidptr_t);
var CFStringCreateWithCharacters = lib.declare(
"CFStringCreateWithCharacters",
ctypes.default_abi,
this.CFStringRef,
ctypes.voidptr_t,
ctypes.jschar.ptr,
ctypes.int32_t);
this.CFStringCreateWithCharacters = function(str) {
var rv = CFStringCreateWithCharacters(null, str, str.length);
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, this.CFRelease);
};
var CFDictionaryGetValue = lib.declare(
"CFDictionaryGetValue",
ctypes.default_abi,
this.CFNumberRef,
this.CFDictionaryRef,
this.CFStringRef);
this.CFDictionaryGetInt = function(dict, str) {
var rv = CFDictionaryGetValue(dict, this.CFStringCreateWithCharacters(str));
if (!rv || rv.isNull()) {
return null;
};
return this.CFNumberGetValue(rv);
};
var CFNumberGetValue = lib.declare(
"CFNumberGetValue",
ctypes.default_abi,
ctypes.bool,
this.CFNumberRef,
ctypes.int32_t,
ctypes.int32_t.ptr);
this.CFNumberGetValue = function(num) {
var rv = new ctypes.int32_t();
CFNumberGetValue(num, 3, rv.address());
console.log("CFNumberGetValue", rv, rv.value);
return rv.value;
};
this.close = function() {
lib.close();
};
})();
var ApplicationServices = new (function() {
var lib = ctypes.open("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices");
var CGSessionCopyCurrentDictionary = lib.declare(
"CGSessionCopyCurrentDictionary",
ctypes.default_abi,
CoreFoundation.CFDictionaryRef);
this.CGSessionCopyCurrentDictionary = function() {
var rv = CGSessionCopyCurrentDictionary();
if (!rv || rv.isNull()) {
return null;
}
return ctypes.CDataFinalizer(rv, CoreFoundation.CFRelease);
};
this.close = function() {
lib.close();
};
})();
setInterval(function() {
var dict = ApplicationServices.CGSessionCopyCurrentDictionary();
if (dict) {
var locked = CoreFoundation.CFDictionaryGetInt(dict, "CGSSessionScreenIsLocked");
console.log("rv", locked);
if (locked) {
// do something;
}
}
}, 500);

Categories