Bug 1208257 - [webext] Extension.jsm support for schemas (r=kmag)

This commit is contained in:
Bill McCloskey 2015-11-16 17:07:48 -08:00
parent 2072ccf5eb
commit 6e9e885005
8 changed files with 324 additions and 38 deletions

View File

@ -39,6 +39,8 @@ XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
"resource://gre/modules/Preferences.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
"resource://gre/modules/Schemas.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
@ -59,6 +61,8 @@ ExtensionManagement.registerScript("chrome://extensions/content/ext-webRequest.j
ExtensionManagement.registerScript("chrome://extensions/content/ext-storage.js");
ExtensionManagement.registerScript("chrome://extensions/content/ext-test.js");
ExtensionManagement.registerSchema("chrome://extensions/content/schemas/cookies.json");
Cu.import("resource://gre/modules/ExtensionUtils.jsm");
var {
LocaleData,
@ -76,17 +80,22 @@ var scriptScope = this;
// This object loads the ext-*.js scripts that define the extension API.
var Management = {
initialized: false,
initialized: null,
scopes: [],
apis: [],
schemaApis: [],
emitter: new EventEmitter(),
// Loads all the ext-*.js scripts currently registered.
lazyInit() {
if (this.initialized) {
return;
return this.initialized;
}
let promises = [];
for (let schema of ExtensionManagement.getSchemas()) {
promises.push(Schemas.load(schema));
}
this.initialized = true;
for (let script of ExtensionManagement.getScripts()) {
let scope = {extensions: this,
@ -98,6 +107,9 @@ var Management = {
// Save the scope to avoid it being garbage collected.
this.scopes.push(scope);
}
this.initialized = Promise.all(promises);
return this.initialized;
},
// Called by an ext-*.js script to register an API. The |api|
@ -119,9 +131,13 @@ var Management = {
this.apis.push({api, permission});
},
registerSchemaAPI(namespace, permission, api) {
this.schemaApis.push({namespace, permission, api});
},
// Mash together into a single object all the APIs registered by the
// functions above. Return the merged object.
generateAPIs(extension, context) {
generateAPIs(extension, context, apis) {
let obj = {};
// Recursively copy properties from source to dest.
@ -138,7 +154,7 @@ var Management = {
}
}
for (let api of this.apis) {
for (let api of apis) {
if (api.permission) {
if (!extension.hasPermission(api.permission)) {
continue;
@ -159,7 +175,6 @@ var Management = {
// Ask to run all the callbacks that are registered for a given hook.
emit(hook, ...args) {
this.lazyInit();
this.emitter.emit(hook, ...args);
},
@ -281,12 +296,30 @@ var GlobalManager = {
},
observe(contentWindow, topic, data) {
function inject(extension, context) {
let inject = (extension, context) => {
let chromeObj = Cu.createObjectIn(contentWindow, {defineAs: "browser"});
contentWindow.wrappedJSObject.chrome = contentWindow.wrappedJSObject.browser;
let api = Management.generateAPIs(extension, context);
let api = Management.generateAPIs(extension, context, Management.apis);
injectAPI(api, chromeObj);
}
let schemaApi = Management.generateAPIs(extension, context, Management.schemaApis);
let schemaWrapper = {
callFunction(ns, name, args) {
return schemaApi[ns][name].apply(null, args);
},
addListener(ns, name, listener, args) {
return schemaApi[ns][name].addListener.call(null, listener, ...args);
},
removeListener(ns, name, listener) {
return schemaApi[ns][name].removeListener.call(null, listener);
},
hasListener(ns, name, listener) {
return schemaApi[ns][name].hasListener.call(null, listener);
},
};
Schemas.inject(chromeObj, schemaWrapper);
};
// Find the add-on associated with this document via the
// principal's originAttributes. This value is computed by
@ -921,7 +954,11 @@ Extension.prototype = extend(Object.create(ExtensionData.prototype), {
return Promise.reject(e);
}
return this.readManifest().then(() => {
let lazyInit = Management.lazyInit();
return lazyInit.then(() => {
return this.readManifest();
}).then(() => {
return this.initLocale();
}).then(() => {
if (this.hasShutdown) {

View File

@ -97,6 +97,19 @@ var Scripts = {
},
};
// Manage the collection of schemas/*.json schemas that define the extension API.
var Schemas = {
schemas: new Set(),
register(schema) {
this.schemas.add(schema);
},
getSchemas() {
return this.schemas;
},
};
// This object manages various platform-level issues related to
// moz-extension:// URIs. It lives here so that it can be used in both
// the parent and child processes.
@ -197,6 +210,9 @@ this.ExtensionManagement = {
registerScript: Scripts.register.bind(Scripts),
getScripts: Scripts.getScripts.bind(Scripts),
registerSchema: Schemas.register.bind(Schemas),
getSchemas: Schemas.getSchemas.bind(Schemas),
getFrameId: Frames.getId.bind(Frames),
getParentFrameId: Frames.getParentId.bind(Frames),
};

View File

@ -28,11 +28,13 @@ function convert(cookie) {
return result;
}
function* query(allDetails, allowed) {
function* query(detailsIn, props) {
// Different callers want to filter on different properties. |props|
// tells us which ones they're interested in.
let details = {};
allowed.map(property => {
if (property in allDetails) {
details[property] = allDetails[property];
props.map(property => {
if (detailsIn[property] !== null) {
details[property] = detailsIn[property];
}
});
@ -135,14 +137,10 @@ function* query(allDetails, allowed) {
}
}
extensions.registerPrivilegedAPI("cookies", (extension, context) => {
extensions.registerSchemaAPI("cookies", "cookies", (extension, context) => {
let self = {
cookies: {
get: function(details, callback) {
if (!details || !details.url || !details.name) {
throw new Error("Mising required property");
}
// FIXME: We don't sort by length of path and creation time.
for (let cookie of query(details, ["url", "name", "storeId"])) {
runSafe(context, callback, convert(cookie));
@ -154,10 +152,6 @@ extensions.registerPrivilegedAPI("cookies", (extension, context) => {
},
getAll: function(details, callback) {
if (!details) {
details = {};
}
let allowed = ["url", "name", "domain", "path", "secure", "session", "storeId"];
let result = [];
for (let cookie of query(details, allowed)) {
@ -168,21 +162,17 @@ extensions.registerPrivilegedAPI("cookies", (extension, context) => {
},
set: function(details, callback) {
if (!details || !details.url) {
throw new Error("Mising required property");
}
let uri = Services.io.newURI(details.url, null, null);
let domain;
if ("domain" in details) {
if (details.domain !== null) {
domain = "." + details.domain;
} else {
domain = uri.host; // "If omitted, the cookie becomes a host-only cookie."
}
let path;
if ("path" in details) {
if (details.path !== null) {
path = details.path;
} else {
// Chrome seems to trim the path after the last slash.
@ -197,11 +187,11 @@ extensions.registerPrivilegedAPI("cookies", (extension, context) => {
}
}
let name = "name" in details ? details.name : "";
let value = "value" in details ? details.value : "";
let secure = "secure" in details ? details.secure : false;
let httpOnly = "httpOnly" in details ? details.httpOnly : false;
let isSession = !("expirationDate" in details);
let name = details.name !== null ? details.name : "";
let value = details.value !== null ? details.value : "";
let secure = details.secure !== null ? details.secure : false;
let httpOnly = details.httpOnly !== null ? details.httpOnly : false;
let isSession = details.expirationDate === null;
let expiry = isSession ? 0 : details.expirationDate;
// Ingore storeID.
@ -212,10 +202,6 @@ extensions.registerPrivilegedAPI("cookies", (extension, context) => {
},
remove: function(details, callback) {
if (!details || !details.name || !details.url) {
throw new Error("Mising required property");
}
for (let cookie of query(details, ["url", "name", "storeId"])) {
Services.cookies.remove(cookie.host, cookie.name, cookie.path, false);
if (callback) {

View File

@ -13,6 +13,8 @@ EXTRA_JS_MODULES += [
'Schemas.jsm',
]
DIRS += ['schemas']
JAR_MANIFESTS += ['jar.mn']
MOCHITEST_MANIFESTS += ['test/mochitest/mochitest.ini']

View File

@ -0,0 +1,27 @@
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,204 @@
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
[
{
"namespace": "cookies",
"description": "Use the <code>browser.cookies</code> API to query and modify cookies, and to be notified when they change.",
"types": [
{
"id": "Cookie",
"type": "object",
"description": "Represents information about an HTTP cookie.",
"properties": {
"name": {"type": "string", "description": "The name of the cookie."},
"value": {"type": "string", "description": "The value of the cookie."},
"domain": {"type": "string", "description": "The domain of the cookie (e.g. \"www.google.com\", \"example.com\")."},
"hostOnly": {"type": "boolean", "description": "True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie)."},
"path": {"type": "string", "description": "The path of the cookie."},
"secure": {"type": "boolean", "description": "True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS)."},
"httpOnly": {"type": "boolean", "description": "True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts)."},
"session": {"type": "boolean", "description": "True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date."},
"expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies."},
"storeId": {"type": "string", "description": "The ID of the cookie store containing this cookie, as provided in getAllCookieStores()."}
}
},
{
"id": "CookieStore",
"type": "object",
"description": "Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a non-incognito window.",
"properties": {
"id": {"type": "string", "description": "The unique identifier for the cookie store."},
"tabIds": {"type": "array", "items": {"type": "integer"}, "description": "Identifiers of all the browser tabs that share this cookie store."}
}
},
{
"id": "OnChangedCause",
"type": "string",
"enum": ["evicted", "expired", "explicit", "expired_overwrite", "overwrite"],
"description": "The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to $(ref:cookies.remove), \"cause\" will be \"explicit\". If a cookie was automatically removed due to expiry, \"cause\" will be \"expired\". If a cookie was removed due to being overwritten with an already-expired expiration date, \"cause\" will be set to \"expired_overwrite\". If a cookie was automatically removed due to garbage collection, \"cause\" will be \"evicted\". If a cookie was automatically removed due to a \"set\" call that overwrote it, \"cause\" will be \"overwrite\". Plan your response accordingly."
}
],
"functions": [
{
"name": "get",
"type": "function",
"description": "Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned.",
"parameters": [
{
"type": "object",
"name": "details",
"description": "Details to identify the cookie being retrieved.",
"properties": {
"url": {"type": "string", "description": "The URL with which the cookie to retrieve is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is simply ignored. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
"name": {"type": "string", "description": "The name of the cookie to retrieve."},
"storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used."}
}
},
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie. This parameter is null if no such cookie was found."
}
]
}
]
},
{
"name": "getAll",
"type": "function",
"description": "Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first.",
"parameters": [
{
"type": "object",
"name": "details",
"description": "Information to filter the cookies being retrieved.",
"properties": {
"url": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those that would match the given URL."},
"name": {"type": "string", "optional": true, "description": "Filters the cookies by name."},
"domain": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose domains match or are subdomains of this one."},
"path": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose path exactly matches this string."},
"secure": {"type": "boolean", "optional": true, "description": "Filters the cookies by their Secure property."},
"session": {"type": "boolean", "optional": true, "description": "Filters out session vs. persistent cookies."},
"storeId": {"type": "string", "optional": true, "description": "The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used."}
}
},
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "cookies", "type": "array", "items": {"$ref": "Cookie"}, "description": "All the existing, unexpired cookies that match the given cookie info."
}
]
}
]
},
{
"name": "set",
"type": "function",
"description": "Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.",
"parameters": [
{
"type": "object",
"name": "details",
"description": "Details about the cookie being set.",
"properties": {
"url": {"type": "string", "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
"name": {"type": "string", "optional": true, "description": "The name of the cookie. Empty by default if omitted."},
"value": {"type": "string", "optional": true, "description": "The value of the cookie. Empty by default if omitted."},
"domain": {"type": "string", "optional": true, "description": "The domain of the cookie. If omitted, the cookie becomes a host-only cookie."},
"path": {"type": "string", "optional": true, "description": "The path of the cookie. Defaults to the path portion of the url parameter."},
"secure": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as Secure. Defaults to false."},
"httpOnly": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as HttpOnly. Defaults to false."},
"expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie."},
"storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store."}
}
},
{
"type": "function",
"name": "callback",
"optional": true,
"parameters": [
{
"name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set. If setting failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set."
}
]
}
]
},
{
"name": "remove",
"type": "function",
"description": "Deletes a cookie by name.",
"parameters": [
{
"type": "object",
"name": "details",
"description": "Information to identify the cookie to remove.",
"properties": {
"url": {"type": "string", "description": "The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
"name": {"type": "string", "description": "The name of the cookie to remove."},
"storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store to look in for the cookie. If unspecified, the cookie is looked for by default in the current execution context's cookie store."}
}
},
{
"type": "function",
"name": "callback",
"optional": true,
"parameters": [
{
"name": "details",
"type": "object",
"description": "Contains details about the cookie that's been removed. If removal failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set.",
"optional": true,
"properties": {
"url": {"type": "string", "description": "The URL associated with the cookie that's been removed."},
"name": {"type": "string", "description": "The name of the cookie that's been removed."},
"storeId": {"type": "string", "description": "The ID of the cookie store from which the cookie was removed."}
}
}
]
}
]
},
{
"name": "getAllCookieStores",
"type": "function",
"description": "Lists all existing cookie stores.",
"parameters": [
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "cookieStores", "type": "array", "items": {"$ref": "CookieStore"}, "description": "All the existing cookie stores."
}
]
}
]
}
],
"events": [
{
"name": "onChanged",
"type": "function",
"description": "Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with \"cause\" of \"overwrite\" . Afterwards, a new cookie is written with the updated values, generating a second notification with \"cause\" \"explicit\".",
"parameters": [
{
"type": "object",
"name": "changeInfo",
"properties": {
"removed": {"type": "boolean", "description": "True if a cookie was removed."},
"cookie": {"$ref": "Cookie", "description": "Information about the cookie that was set or removed."},
"cause": {"$ref": "OnChangedCause", "description": "The underlying reason behind the cookie's change."}
}
}
]
}
]
}
]

View File

@ -0,0 +1,7 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
toolkit.jar:
% content extensions %content/extensions/
content/extensions/schemas/cookies.json

View File

@ -0,0 +1,7 @@
# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
JAR_MANIFESTS += ['jar.mn']