diff --git a/src/index.html b/src/index.html index f2ea95e..10719f8 100644 --- a/src/index.html +++ b/src/index.html @@ -18,6 +18,8 @@

+ + diff --git a/src/js/components/KeptApp.js b/src/js/components/KeptApp.js index 0dbfb9e..77c3636 100644 --- a/src/js/components/KeptApp.js +++ b/src/js/components/KeptApp.js @@ -16,10 +16,19 @@ var KeptApp = React.createClass({ getInitialState: function() { return { - items: this.props.store.load() + items: [] }; }, + componentDidMount: function() { + this.props.store.load() + .then(function(items) { + this.setState({ + items: items + }); + }.bind(this)); + }, + /** * Provided for the UndoStack mixin. */ @@ -56,13 +65,15 @@ var KeptApp = React.createClass({ }, save: function(items) { - this.props.store.save(items); - this.snapshot(); - this.setState({items: items}); + return this.props.store.save(items) + .then(function() { + this.snapshot(); + this.setState({items: items}); + }.bind(this)); }, loadSamples: function() { - this.save(initial); + return this.save(initial); }, formCreator: function(type) { @@ -80,9 +91,9 @@ var KeptApp = React.createClass({ }, create: function(itemData) { - itemData.id = utils.nextId(this.state.items); - this.save(this.state.items.concat([itemData])); - this.resetForm(); + itemData.id = utils.nextId(); + return this.save(this.state.items.concat([itemData])) + .then(this.resetForm.bind(this)); }, edit: function(itemData) { @@ -90,16 +101,17 @@ var KeptApp = React.createClass({ }, update: function(updatedItem) { - this.save(this.state.items.map(function(item) { + return this.save(this.state.items.map(function(item) { if (item.id === updatedItem.id) return updatedItem; return item; - })); - this.resetForm(); + })).then(function() { + this.resetForm(); + }.bind(this)); }, remove: function(itemData) { - this.save(this.state.items.filter(function(data) { + return this.save(this.state.items.filter(function(data) { return itemData !== data; })); }, @@ -107,7 +119,7 @@ var KeptApp = React.createClass({ move: function(fromIndex, toIndex) { var items = this.state.items.slice(0); items.splice(toIndex, 0, items.splice(fromIndex, 1)[0]); - this.save(items); + return this.save(items); }, render: function() { diff --git a/src/js/data/daybed_schema.json b/src/js/data/daybed_schema.json new file mode 100644 index 0000000..f501791 --- /dev/null +++ b/src/js/data/daybed_schema.json @@ -0,0 +1,52 @@ +{ + "text": { + "title": "Keep — Text", + "description": "Store user text kept card.", + "fields": [ + { + "name": "title", + "type": "string", + "label": "Title", + "required": true + }, + { + "name": "text", + "type": "text", + "label": "Text", + "required": true + } + ] + }, + "todo": { + "title": "Keep — Todo", + "description": "Store user text kept card.", + "fields": [ + { + "name": "title", + "type": "string", + "label": "Title", + "required": true + }, + { + "name": "tasks", + "type": "list", + "label": "Tasks", + "description": "List of todo list's tasks.", + "fields": [ + { + "name": "label", + "type": "string", + "label": "Label", + "required": true + }, + { + "name": "done", + "type": "boolean", + "label": "Check when done!", + "required": true + } + ] + } + ] + } +} diff --git a/src/js/data/definition b/src/js/data/definition new file mode 100644 index 0000000..30b100a --- /dev/null +++ b/src/js/data/definition @@ -0,0 +1,33 @@ +{"definition": { + "title": "Keep — Todo", + "description": "Store user text kept card.", + "fields": [ + { + "name": "title", + "type": "string", + "label": "Title", + "required": true + }, + { + "name": "tasks", + "type": "list", + "label": "Tasks", + "description": "List of todo list's tasks.", + "fields": [ + { + "name": "label", + "type": "string", + "label": "Label", + "required": true + }, + { + "name": "done", + "type": "boolean", + "label": "Check when done!", + "required": true + } + ] + } + ] + } +} diff --git a/src/js/data/record b/src/js/data/record new file mode 100644 index 0000000..4e02f4d --- /dev/null +++ b/src/js/data/record @@ -0,0 +1,8 @@ +{ + "title": "Today", + "tasks": [ + {"label": "Walk the dog", "done": true}, + {"label": "Clean the car", "done": false}, + {"label": "Buy a new carpet", "done": false} + ] +} diff --git a/src/js/kept.js b/src/js/kept.js index d8ff739..cf024e3 100644 --- a/src/js/kept.js +++ b/src/js/kept.js @@ -5,7 +5,14 @@ var React = require("react"); var KeptApp = require("./components/KeptApp"); var KeptStore = require("./store"); -var store = new KeptStore(); - -React.renderComponent(, - document.getElementById('kept')); +var DaybedStore = require("./store/daybed"); +// var store = new KeptStore(); +var store = new DaybedStore({ + "host": "http://localhost:8000", + "tokenId": "8ac94860337bcd6497bc6dd7c17836f2ce027fb442666ee8bace96c8c58e3594", + "tokenKey": "1d24f64c424cdefe4797a13c1d43b73d20988c803a1dcf80a684e6cd336db31e" +}); +store.setUp().then(function() { + React.renderComponent(, + document.getElementById('kept')); +}); diff --git a/src/js/store/daybed.js b/src/js/store/daybed.js new file mode 100644 index 0000000..8a87725 --- /dev/null +++ b/src/js/store/daybed.js @@ -0,0 +1,127 @@ +"use strict"; +var PREFIX = "keep_"; // Schema table prefix +var schema = require("../data/daybed_schema"); +var objectEquals = require("../utils").objectEquals; + + +function DaybedStore(options) { + if (!options.hasOwnProperty("host")) { + throw new Error("Please define your Daybed storage host urls."); + } + if (!options.hasOwnProperty("tokenId") || + !options.hasOwnProperty("tokenKey")) { + throw new Error("Please define your Daybed credentials " + + "(tokenId, tokenKey)."); + } + this._types = Object.keys(schema); + + this._store = new Daybed.Session(options.host, { + id: options.tokenId, + key: options.tokenKey, + algorithm: "sha256" + }); +} + + +DaybedStore.prototype = { + setUp: function() { + return this._store.getModels() + .then(function(models) { + // Make sure all needed models are defined. + var modelIds = []; + models.forEach(function(doc) { + modelIds.push(doc.id); + }); + return Promise.all(this._types.map(function(type) { + var daybedModelName = PREFIX + type; + if (modelIds.indexOf(daybedModelName) === -1) { + // If not create the model + return this._store.addModel(daybedModelName, schema[type]) + .catch(function(err) { + console.error("Add model", daybedModelName, ":", err); + throw new Error("Add model " + daybedModelName + ": " + err); + }); + } else { + console.log("Model", daybedModelName, "already exists."); + } + }.bind(this))); + }.bind(this)); + }, + load: function() { + var data = []; + return Promise.all(this._types.map(function(type) { + return this._store.getRecords(PREFIX + type) + .then(function(doc) { + data = data.concat(doc.records.map(function(record) { + record.type = type; + return record; + })); + }) + .catch(console.error); + }.bind(this))) + .then(function() { + return data; + }); + }, + + save: function(data) { + console.log(data); + var self = this; + var currentDataObj = {}, + previousDataObj = {}, + currentDataIds, previousDataIds, + droppedObjIds, changedObjIds; + + return self.load() + .then(function(items) { + console.log(items); + // Get current data ids + currentDataIds = data.map(function(doc) { + currentDataObj[doc.id] = doc; + return doc.id; + }); + + previousDataIds = items.map(function(doc) { + previousDataObj[doc.id] = doc; + return doc.id + }); + + // Get deleted objects + droppedObjIds = previousDataIds.filter(function(docId) { + return currentDataIds.indexOf(docId) < 0; + }); + + // Get changed objects + changedObjIds = currentDataIds.filter(function(docId) { + console.log(docId, currentDataObj[docId], previousDataObj[docId], + objectEquals(currentDataObj[docId], previousDataObj[docId])); + return objectEquals(currentDataObj[docId], previousDataObj[docId]) !== true; + }); + + // Make the change to the backend + return Promise.all(changedObjIds.map(function(docId) { + var doc = currentDataObj[docId]; + var daybedModelName; + try { + doc = JSON.parse(JSON.stringify(doc)); + daybedModelName = PREFIX + doc.type; + delete doc.type; + } catch (e) { + console.error(doc, "failed saving keep data", e); + return; + } + return self._store.addRecord(daybedModelName, doc) + .catch(console.error); + })).then(function() { + return Promise.all(droppedObjIds.map(function(docId) { + var doc = previousDataObj[docId]; + var daybedModelName = PREFIX + doc.type; + return self._store.deleteRecord(daybedModelName, docId) + .catch(console.error); + })); + }); + }); + } +}; + +module.exports = DaybedStore; diff --git a/src/js/store/index.js b/src/js/store/index.js index 8ba0a09..3d5cc12 100644 --- a/src/js/store/index.js +++ b/src/js/store/index.js @@ -7,25 +7,30 @@ function KeptStore(options) { KeptStore.prototype = { load: function() { - var data = this._store.getItem("keep.data"); - if (!data) { - console.error("empty stored kept data:", data); - return []; - } - try { - return JSON.parse(data) || []; - } catch (e) { - console.error("failed parsing kept data:", data, e); - return []; - } + return new Promise(function(resolve, reject) { + var data = this._store.getItem("keep.data"); + if (!data) { + console.error("empty stored kept data:", data); + resolve([]); + } + try { + resolve(JSON.parse(data) || []); + } catch (e) { + console.error("failed parsing kept data:", data, e); + resolve([]); + } + }.bind(this)); }, save: function(data) { - try { - this._store["keep.data"] = JSON.stringify(data); - } catch (e) { - console.error("failed saving keep data", e); - } + return new Promise(function(resolve, reject) { + try { + this._store["keep.data"] = JSON.stringify(data); + } catch (e) { + console.error("failed saving keep data", e); + } + resolve(); + }.bind(this)); } }; diff --git a/src/js/utils/__tests__/utils-test.js b/src/js/utils/__tests__/utils-test.js index 02e7d65..015a81b 100644 --- a/src/js/utils/__tests__/utils-test.js +++ b/src/js/utils/__tests__/utils-test.js @@ -4,17 +4,17 @@ jest.dontMock('..'); var utils = require('..'); describe("nextId", function() { - var items; - beforeEach(function() { - items = [{id: 1}]; + it("should create an uuid", function() { + expect(utils.nextId().length).toEqual(36); }); +}); - it("should create a next id if items list is empty", function() { - expect(utils.nextId([])).toEqual(1); - }); - it("should find the next available id", function() { - expect(utils.nextId(items)).toEqual(2); +describe("objectEquals", function() { + it("should test objects equality", function() { + expect(utils.objectEquals( + {b: "Toto", a: "Titi"}, {a: "Titi", b: "Toto"} + )).toEqual(true); }); }); diff --git a/src/js/utils/index.js b/src/js/utils/index.js index 038aeda..6e11ac9 100644 --- a/src/js/utils/index.js +++ b/src/js/utils/index.js @@ -5,9 +5,54 @@ function clone(o) { } exports.clone = clone; -function nextId(items) { - return Math.max.apply(null, items.concat([0]).map(function(item) { - return item.id || 0; - })) + 1; + +function objectEquals(x, y) { + // if both x and y are null or undefined and exactly the same + if (x === y) return true; + + // if they are not strictly equal, they both need to be Objects + if (!(x instanceof Object) || !(y instanceof Object)) return false; + + // they must have the exact same prototype chain, the closest we can + // do is test there constructor. + if (x.constructor !== y.constructor) return false; + + for (var p in x) { + // other properties were tested using x.constructor === y.constructor + if (!x.hasOwnProperty(p)) continue; + + // allows to compare x[p] and y[p] when set to undefined + if (!y.hasOwnProperty(p)) return false; + + // if they have the same strict value or identity then they are equal + if (x[p] === y[p]) continue; + + if (typeof(x[p]) !== "object") return false; + // Numbers, Strings, Functions, Booleans must be strictly equal + + // Objects and Arrays must be tested recursively + if (!objectEquals(x[p], y[p])) return false; + } + + for (p in y) { + // allows x[p] to be set to undefined + if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) return false; + } + return true; +} + +exports.objectEquals = objectEquals; + + +// UUID management +function s4() { + return Math.floor((1 + Math.random()) * 0x10000) + .toString(16) + .substring(1); +} + +function nextId() { + return s4() + s4() + '-' + s4() + '-' + s4() + '-' + + s4() + '-' + s4() + s4() + s4(); } exports.nextId = nextId; diff --git a/src/js/vendor/daybed.js b/src/js/vendor/daybed.js new file mode 100644 index 0000000..5862880 --- /dev/null +++ b/src/js/vendor/daybed.js @@ -0,0 +1,311 @@ +/* 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/. */ + +(function(exports) { + + "use strict"; + + var TIMEOUT = 15000; + + function request(options) { + return new Promise(function(resolve, reject) { + var req = new XMLHttpRequest(); + req.open(options.method, options.url, true); + req.setRequestHeader('Content-Type', 'application/json'); + req.setRequestHeader('Accept', 'application/json'); + req.responseType = 'json'; + req.timeout = TIMEOUT; + // req.withCredentials = true; + + if (options.validateOnly) { + req.setRequestHeader('Validate-Only', 'true'); + } + + if (options.credentials) { + var hawkHeader = hawk.client.header(options.url, options.method, { + credentials: options.credentials + }); + req.setRequestHeader('authorization', hawkHeader.field); + } + req.onload = function() { + if (!("" + req.status).match(/^2/)) { + reject(req.response); + return; + } + resolve(req.response); + }; + + req.onerror = req.ontimeout = function(event) { + reject(event.target.status); + }; + + var body; + if (options.body) { + body = JSON.stringify(options.body); + } + + req.send(body); + }); + } + + function getToken(daybedUrl) { + return request({ + method: "POST", + url: daybedUrl + "/tokens" + }); + } + + function availableFields(host) { + return request({ + method: "GET", + url: host + "/fields" + }); + } + + function spore(host) { + return request({ + method: "GET", + url: host + "/spore" + }); + } + + + function Session(host, credentials, options) { + if (host === undefined) { + throw new Error("You should provide an host."); + } + + if (credentials === undefined || + !credentials.hasOwnProperty("id") || credentials.id === undefined || + !credentials.hasOwnProperty("key") || credentials.key === undefined) { + credentials = undefined; + } + + this.host = host; + this.credentials = credentials; + this.credentials.algorithm = "sha256"; + this.options = options; + } + + Session.prototype = { + hello: function() { + return request({ + method: "GET", + url: this.host + "/", + credentials: this.credentials + }); + }, + + getModels: function() { + return request({ + method: "GET", + url: this.host + "/models", + credentials: this.credentials + }).then(function(doc) { + return doc.models; + }); + }, + + addModel: function(modelname, definition, records) { + var url, method; + + if (modelname === undefined) { + method = "POST"; + url = this.host + "/models"; + } else { + method = "PUT"; + url = this.host + "/models/" + modelname; + } + + return request({ + method: method, + url: url, + body: {definition: definition, records: records}, + credentials: this.credentials + }); + }, + + getModel: function(modelname) { + return request({ + method: "GET", + url: this.host + "/models/" + modelname, + credentials: this.credentials + }); + }, + + deleteModel: function(modelname) { + return request({ + method: "DELETE", + url: this.host + "/models/" + modelname, + credentials: this.credentials + }); + }, + + getDefinition: function(modelname) { + return request({ + method: "GET", + url: this.host + "/models/" + modelname + "/definition", + credentials: this.credentials + }); + }, + + getPermissions: function(modelname) { + return request({ + method: "GET", + url: this.host + "/models/" + modelname + "/permissions", + credentials: this.credentials + }); + }, + + putPermissions: function(modelname, permissions) { + return request({ + method: "PUT", + url: this.host + "/models/" + modelname + "/permissions", + body: permissions, + credentials: this.credentials + }); + }, + + patchPermissions: function(modelname, rules) { + return request({ + method: "PATCH", + url: this.host + "/models/" + modelname + "/permissions", + body: rules, + credentials: this.credentials + }); + }, + + getRecords: function(modelname) { + return request({ + method: "GET", + url: this.host + "/models/" + modelname + "/records", + credentials: this.credentials + }); + }, + + deleteRecords: function(modelname) { + return request({ + method: "DELETE", + url: this.host + "/models/" + modelname + "/records", + credentials: this.credentials + }); + }, + + getRecord: function(modelname, recordId) { + return request({ + method: "GET", + url: this.host + "/models/" + modelname + "/records/" + recordId, + credentials: this.credentials + }); + }, + + addRecord: function(modelname, record) { + var url, method; + + if (!record.hasOwnProperty("id") || !record.id) { + method = "POST"; + url = this.host + "/models/" + modelname + "/records"; + } else { + method = "PUT"; + url = this.host + "/models/" + modelname + "/records/" + record.id; + } + + return request({ + method: method, + url: url, + body: record, + credentials: this.credentials + }); + }, + + validateRecord: function(modelname, record) { + var url, method; + + if (!record.hasOwnProperty("id")) { + method = "POST"; + url = this.host + "/models/" + modelname + "/records"; + } else { + method = "PUT"; + url = this.host + "/models/" + modelname + "/records/" + record.id; + } + + return request({ + method: method, + url: url, + body: record, + validateOnly: true, + credentials: this.credentials + }); + }, + + patchRecord: function(modelname, recordId, patch) { + return request({ + method: "PATCH", + url: this.host + "/models/" + modelname + "/records/" + recordId, + body: patch, + credentials: this.credentials + }); + }, + + deleteRecord: function(modelname, recordId) { + return request({ + method: "DELETE", + url: this.host + "/models/" + modelname + "/records/" + recordId, + credentials: this.credentials + }); + } + }; + + + function Model(session, modelname, definition, records) { + this.session = session; + this.modelname = modelname; + + this._definition = definition; + this._records = records || []; + } + + Model.prototype = { + load: function() { + var self = this; + return new Promise(function(resolve, reject) { + self.session.getModel(self.modelname).then(function(resp) { + console.debug(self._definition, "has been replaced by", resp.definition); + console.debug(self._records, "has been replaced by", resp.records); + + self._definition = resp.definition; + self._records = resp.records; + resolve(); + }).catch(reject); + }); + }, + add: function(record) { + this._records.push(record); + }, + definition: function() { + return this._definition; + }, + records: function() { + return this._records; + }, + save: function() { + return this.session.addModel(this.modelname, this._definition, this._records); + }, + delete: function() { + return this.session.deleteModel(this.modelname); + } + }; + + + var Daybed = { + getToken: getToken, + availableFields: availableFields, + spore: spore, + Session: Session, + Model: Model + }; + + exports.Daybed = Daybed; + +})(this); diff --git a/src/js/vendor/hawk.js b/src/js/vendor/hawk.js new file mode 100644 index 0000000..3369943 --- /dev/null +++ b/src/js/vendor/hawk.js @@ -0,0 +1,514 @@ +/* + HTTP Hawk Authentication Scheme + Copyright (c) 2012-2013, Eran Hammer + MIT Licensed +*/ + + +// Declare namespace + +var hawk = {}; + + +// Export if used as a module + +if (typeof module !== "undefined" && module.exports) { + module.exports = hawk; +} + +hawk.client = { + + // Generate an Authorization header for a given request + + /* + uri: 'http://example.com/resource?a=b' + method: HTTP verb (e.g. 'GET', 'POST') + options: { + + // Required + + credentials: { + id: 'dh37fgj492je', + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + + // Optional + + ext: 'application-specific', // Application specific data sent via the ext attribute + timestamp: Date.now() / 1000, // A pre-calculated timestamp in seconds + nonce: '2334f34f', // A pre-generated nonce + localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided) + payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided) + contentType: 'application/json', // Payload content-type (ignored if hash provided) + hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash + app: '24s23423f34dx', // Oz application id + dlg: '234sz34tww3sd' // Oz delegated-by application id + } + */ + + header: function (uri, method, options) { + + var result = { + field: '', + artifacts: {} + }; + + // Validate inputs + + if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') || + !method || typeof method !== 'string' || + !options || typeof options !== 'object') { + + result.err = 'Invalid argument type'; + return result; + } + + // Application time + + var timestamp = options.timestamp || Math.floor((hawk.utils.now() + (options.localtimeOffsetMsec || 0)) / 1000) + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + result.err = 'Invalid credential object'; + return result; + } + + if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) { + result.err = 'Unknown algorithm'; + return result; + } + + // Parse URI + + if (typeof uri === 'string') { + uri = hawk.utils.parseUri(uri); + } + + // Calculate signature + + var artifacts = { + ts: timestamp, + nonce: options.nonce || hawk.utils.randomString(6), + method: method, + resource: uri.relative, + host: uri.hostname, + port: uri.port, + hash: options.hash, + ext: options.ext, + app: options.app, + dlg: options.dlg + }; + + result.artifacts = artifacts; + + // Calculate payload hash + + if (!artifacts.hash && + options.hasOwnProperty('payload')) { + + artifacts.hash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType); + } + + var mac = hawk.crypto.calculateMac('header', credentials, artifacts); + + // Construct header + + var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed + var header = 'Hawk id="' + credentials.id + + '", ts="' + artifacts.ts + + '", nonce="' + artifacts.nonce + + (artifacts.hash ? '", hash="' + artifacts.hash : '') + + (hasExt ? '", ext="' + hawk.utils.escapeHeaderAttribute(artifacts.ext) : '') + + '", mac="' + mac + '"'; + + if (artifacts.app) { + header += ', app="' + artifacts.app + + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'; + } + + result.field = header; + + return result; + }, + + + // Validate server response + + /* + request: object created via 'new XMLHttpRequest()' after response received + artifacts: object recieved from header().artifacts + options: { + payload: optional payload received + required: specifies if a Server-Authorization header is required. Defaults to 'false' + } + */ + + authenticate: function (request, credentials, artifacts, options) { + + options = options || {}; + + var getHeader = function (name) { + + return request.getResponseHeader ? request.getResponseHeader(name) : request.getHeader(name); + }; + + if (getHeader('www-authenticate')) { + + // Parse HTTP WWW-Authenticate header + + var attributes = hawk.utils.parseAuthorizationHeader(getHeader('www-authenticate'), ['ts', 'tsm', 'error']); + if (!attributes) { + return false; + } + + if (attributes.ts) { + var tsm = hawk.crypto.calculateTsMac(attributes.ts, credentials); + if (tsm !== attributes.tsm) { + return false; + } + + hawk.utils.setNtpOffset(attributes.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision + } + } + + // Parse HTTP Server-Authorization header + + if (!getHeader('server-authorization') && + !options.required) { + + return true; + } + + var attributes = hawk.utils.parseAuthorizationHeader(getHeader('server-authorization'), ['mac', 'ext', 'hash']); + if (!attributes) { + return false; + } + + var modArtifacts = { + ts: artifacts.ts, + nonce: artifacts.nonce, + method: artifacts.method, + resource: artifacts.resource, + host: artifacts.host, + port: artifacts.port, + hash: attributes.hash, + ext: attributes.ext, + app: artifacts.app, + dlg: artifacts.dlg + }; + + var mac = hawk.crypto.calculateMac('response', credentials, modArtifacts); + if (mac !== attributes.mac) { + return false; + } + + if (!options.hasOwnProperty('payload')) { + return true; + } + + if (!attributes.hash) { + return false; + } + + var calculatedHash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, getHeader('content-type')); + return (calculatedHash === attributes.hash); + }, + + message: function (host, port, message, options) { + + // Validate inputs + + if (!host || typeof host !== 'string' || + !port || typeof port !== 'number' || + message === null || message === undefined || typeof message !== 'string' || + !options || typeof options !== 'object') { + + return null; + } + + // Application time + + var timestamp = options.timestamp || Math.floor((hawk.utils.now() + (options.localtimeOffsetMsec || 0)) / 1000) + + // Validate credentials + + var credentials = options.credentials; + if (!credentials || + !credentials.id || + !credentials.key || + !credentials.algorithm) { + + // Invalid credential object + return null; + } + + if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) { + return null; + } + + // Calculate signature + + var artifacts = { + ts: timestamp, + nonce: options.nonce || hawk.utils.randomString(6), + host: host, + port: port, + hash: hawk.crypto.calculatePayloadHash(message, credentials.algorithm) + }; + + // Construct authorization + + var result = { + id: credentials.id, + ts: artifacts.ts, + nonce: artifacts.nonce, + hash: artifacts.hash, + mac: hawk.crypto.calculateMac('message', credentials, artifacts) + }; + + return result; + }, + + authenticateTimestamp: function (message, credentials, updateClock) { // updateClock defaults to true + + var tsm = hawk.crypto.calculateTsMac(message.ts, credentials); + if (tsm !== message.tsm) { + return false; + } + + if (updateClock !== false) { + hawk.utils.setNtpOffset(message.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision + } + + return true; + } +}; + + +hawk.crypto = { + + headerVersion: '1', + + algorithms: ['sha1', 'sha256'], + + calculateMac: function (type, credentials, options) { + + var normalized = hawk.crypto.generateNormalizedString(type, options); + + var hmac = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()](normalized, credentials.key); + return hmac.toString(CryptoJS.enc.Base64); + }, + + generateNormalizedString: function (type, options) { + + var normalized = 'hawk.' + hawk.crypto.headerVersion + '.' + type + '\n' + + options.ts + '\n' + + options.nonce + '\n' + + (options.method || '').toUpperCase() + '\n' + + (options.resource || '') + '\n' + + options.host.toLowerCase() + '\n' + + options.port + '\n' + + (options.hash || '') + '\n'; + + if (options.ext) { + normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n'); + } + + normalized += '\n'; + + if (options.app) { + normalized += options.app + '\n' + + (options.dlg || '') + '\n'; + } + + return normalized; + }, + + calculatePayloadHash: function (payload, algorithm, contentType) { + + var hash = CryptoJS.algo[algorithm.toUpperCase()].create(); + hash.update('hawk.' + hawk.crypto.headerVersion + '.payload\n'); + hash.update(hawk.utils.parseContentType(contentType) + '\n'); + hash.update(payload || ''); + hash.update('\n'); + return hash.finalize().toString(CryptoJS.enc.Base64); + }, + + calculateTsMac: function (ts, credentials) { + + var hash = CryptoJS['Hmac' + credentials.algorithm.toUpperCase()]('hawk.' + hawk.crypto.headerVersion + '.ts\n' + ts + '\n', credentials.key); + return hash.toString(CryptoJS.enc.Base64); + } +}; + + +hawk.utils = { + + storage: { // localStorage compatible interface + _cache: {}, + setItem: function (key, value) { + + hawk.utils.storage._cache[key] = value; + }, + getItem: function (key) { + + return hawk.utils.storage._cache[key]; + } + }, + + setStorage: function (storage) { + + var ntpOffset = hawk.utils.getNtpOffset() || 0; + hawk.utils.storage = storage; + hawk.utils.setNtpOffset(ntpOffset); + }, + + setNtpOffset: function (offset) { + + try { + hawk.utils.storage.setItem('hawk_ntp_offset', offset); + } + catch (err) { + console.error('[hawk] could not write to storage.'); + console.error(err); + } + }, + + getNtpOffset: function () { + + return parseInt(hawk.utils.storage.getItem('hawk_ntp_offset') || '0', 10); + }, + + now: function () { + + return (new Date()).getTime() + hawk.utils.getNtpOffset(); + }, + + escapeHeaderAttribute: function (attribute) { + + return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); + }, + + parseContentType: function (header) { + + if (!header) { + return ''; + } + + return header.split(';')[0].replace(/^\s+|\s+$/g, '').toLowerCase(); + }, + + parseAuthorizationHeader: function (header, keys) { + + if (!header) { + return null; + } + + var headerParts = header.match(/^(\w+)(?:\s+(.*))?$/); // Header: scheme[ something] + if (!headerParts) { + return null; + } + + var scheme = headerParts[1]; + if (scheme.toLowerCase() !== 'hawk') { + return null; + } + + var attributesString = headerParts[2]; + if (!attributesString) { + return null; + } + + var attributes = {}; + var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) { + + // Check valid attribute names + + if (keys.indexOf($1) === -1) { + return; + } + + // Allowed attribute value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9 + + if ($2.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/) === null) { + return; + } + + // Check for duplicates + + if (attributes.hasOwnProperty($1)) { + return; + } + + attributes[$1] = $2; + return ''; + }); + + if (verify !== '') { + return null; + } + + return attributes; + }, + + randomString: function (size) { + + var randomSource = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + var len = randomSource.length; + + var result = []; + for (var i = 0; i < size; ++i) { + result[i] = randomSource[Math.floor(Math.random() * len)]; + } + + return result.join(''); + }, + + parseUri: function (input) { + + // Based on: parseURI 1.2.2 + // http://blog.stevenlevithan.com/archives/parseuri + // (c) Steven Levithan + // MIT License + + var keys = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'hostname', 'port', 'resource', 'relative', 'pathname', 'directory', 'file', 'query', 'fragment']; + + var uriRegex = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?)(?:#(.*))?)/; + var uriByNumber = uriRegex.exec(input); + var uri = {}; + + var i = 15; + while (i--) { + uri[keys[i]] = uriByNumber[i] || ''; + } + + if (uri.port === null || + uri.port === '') { + + uri.port = (uri.protocol.toLowerCase() === 'http' ? '80' : (uri.protocol.toLowerCase() === 'https' ? '443' : '')); + } + + return uri; + } +}; + + +// Based on: Crypto-JS v3.1.2 +// Copyright (c) 2009-2013, Jeff Mott. All rights reserved. +// http://code.google.com/p/crypto-js/ +// http://code.google.com/p/crypto-js/wiki/License + +var CryptoJS = CryptoJS || function (h, r) { var k = {}, l = k.lib = {}, n = function () { }, f = l.Base = { extend: function (a) { n.prototype = this; var b = new n; a && b.mixIn(a); b.hasOwnProperty("init") || (b.init = function () { b.$super.init.apply(this, arguments) }); b.init.prototype = b; b.$super = this; return b }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var b in a) a.hasOwnProperty(b) && (this[b] = a[b]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, j = l.WordArray = f.extend({ init: function (a, b) { a = this.words = a || []; this.sigBytes = b != r ? b : 4 * a.length }, toString: function (a) { return (a || s).stringify(this) }, concat: function (a) { var b = this.words, d = a.words, c = this.sigBytes; a = a.sigBytes; this.clamp(); if (c % 4) for (var e = 0; e < a; e++) b[c + e >>> 2] |= (d[e >>> 2] >>> 24 - 8 * (e % 4) & 255) << 24 - 8 * ((c + e) % 4); else if (65535 < d.length) for (e = 0; e < a; e += 4) b[c + e >>> 2] = d[e >>> 2]; else b.push.apply(b, d); this.sigBytes += a; return this }, clamp: function () { var a = this.words, b = this.sigBytes; a[b >>> 2] &= 4294967295 << 32 - 8 * (b % 4); a.length = h.ceil(b / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var b = [], d = 0; d < a; d += 4) b.push(4294967296 * h.random() | 0); return new j.init(b, a) } }), m = k.enc = {}, s = m.Hex = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) { var e = b[c >>> 2] >>> 24 - 8 * (c % 4) & 255; d.push((e >>> 4).toString(16)); d.push((e & 15).toString(16)) } return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c += 2) d[c >>> 3] |= parseInt(a.substr(c, 2), 16) << 24 - 4 * (c % 8); return new j.init(d, b / 2) } }, p = m.Latin1 = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) d.push(String.fromCharCode(b[c >>> 2] >>> 24 - 8 * (c % 4) & 255)); return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c++) d[c >>> 2] |= (a.charCodeAt(c) & 255) << 24 - 8 * (c % 4); return new j.init(d, b) } }, t = m.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(p.stringify(a))) } catch (b) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return p.parse(unescape(encodeURIComponent(a))) } }, q = l.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new j.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = t.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var b = this._data, d = b.words, c = b.sigBytes, e = this.blockSize, f = c / (4 * e), f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); a = f * e; c = h.min(4 * a, c); if (a) { for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); g = d.splice(0, a); b.sigBytes -= c } return new j.init(g, c) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); l.Hasher = q.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { q.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, d) { return (new a.init(d)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, d) { return (new u.HMAC.init(a, d)).finalize(b) } } }); var u = k.algo = {}; return k }(Math); +(function () { var k = CryptoJS, b = k.lib, m = b.WordArray, l = b.Hasher, d = [], b = k.algo.SHA1 = l.extend({ _doReset: function () { this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (n, p) { for (var a = this._hash.words, e = a[0], f = a[1], h = a[2], j = a[3], b = a[4], c = 0; 80 > c; c++) { if (16 > c) d[c] = n[p + c] | 0; else { var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16]; d[c] = g << 1 | g >>> 31 } g = (e << 5 | e >>> 27) + b + d[c]; g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514); b = j; j = h; h = f << 30 | f >>> 2; f = e; e = g } a[0] = a[0] + e | 0; a[1] = a[1] + f | 0; a[2] = a[2] + h | 0; a[3] = a[3] + j | 0; a[4] = a[4] + b | 0 }, _doFinalize: function () { var b = this._data, d = b.words, a = 8 * this._nDataBytes, e = 8 * b.sigBytes; d[e >>> 5] |= 128 << 24 - e % 32; d[(e + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296); d[(e + 64 >>> 9 << 4) + 15] = a; b.sigBytes = 4 * d.length; this._process(); return this._hash }, clone: function () { var b = l.clone.call(this); b._hash = this._hash.clone(); return b } }); k.SHA1 = l._createHelper(b); k.HmacSHA1 = l._createHmacHelper(b) })(); +(function (k) { for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t = [], u = function (q) { return 4294967296 * (q - (q | 0)) | 0 }, l = 2, b = 0; 64 > b;) { var d; a: { d = l; for (var w = k.sqrt(d), r = 2; r <= w; r++) if (!(d % r)) { d = !1; break a } d = !0 } d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t[b] = u(k.pow(l, 1 / 3)), b++); l++ } var n = [], h = h.SHA256 = j.extend({ _doReset: function () { this._hash = new v.init(s.slice(0)) }, _doProcessBlock: function (q, h) { for (var a = this._hash.words, c = a[0], d = a[1], b = a[2], k = a[3], f = a[4], g = a[5], j = a[6], l = a[7], e = 0; 64 > e; e++) { if (16 > e) n[e] = q[h + e] | 0; else { var m = n[e - 15], p = n[e - 2]; n[e] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n[e - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n[e - 16] } m = l + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g ^ ~f & j) + t[e] + n[e]; p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d ^ c & b ^ d & b); l = j; j = g; g = f; f = k + m | 0; k = b; b = d; d = c; c = m + p | 0 } a[0] = a[0] + c | 0; a[1] = a[1] + d | 0; a[2] = a[2] + b | 0; a[3] = a[3] + k | 0; a[4] = a[4] + f | 0; a[5] = a[5] + g | 0; a[6] = a[6] + j | 0; a[7] = a[7] + l | 0 }, _doFinalize: function () { var d = this._data, b = d.words, a = 8 * this._nDataBytes, c = 8 * d.sigBytes; b[c >>> 5] |= 128 << 24 - c % 32; b[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296); b[(c + 64 >>> 9 << 4) + 15] = a; d.sigBytes = 4 * b.length; this._process(); return this._hash }, clone: function () { var b = j.clone.call(this); b._hash = this._hash.clone(); return b } }); g.SHA256 = j._createHelper(h); g.HmacSHA256 = j._createHmacHelper(h) })(Math); +(function () { var c = CryptoJS, k = c.enc.Utf8; c.algo.HMAC = c.lib.Base.extend({ init: function (a, b) { a = this._hasher = new a.init; "string" == typeof b && (b = k.parse(b)); var c = a.blockSize, e = 4 * c; b.sigBytes > e && (b = a.finalize(b)); b.clamp(); for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c; d++) h[d] ^= 1549556828, j[d] ^= 909522486; f.sigBytes = g.sigBytes = e; this.reset() }, reset: function () { var a = this._hasher; a.reset(); a.update(this._iKey) }, update: function (a) { this._hasher.update(a); return this }, finalize: function (a) { var b = this._hasher; a = b.finalize(a); b.reset(); return b.finalize(this._oKey.clone().concat(a)) } }) })(); +(function () { var h = CryptoJS, j = h.lib.WordArray; h.enc.Base64 = { stringify: function (b) { var e = b.words, f = b.sigBytes, c = this._map; b.clamp(); b = []; for (var a = 0; a < f; a += 3) for (var d = (e[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63)); if (e = c.charAt(64)) for (; b.length % 4;) b.push(e); return b.join("") }, parse: function (b) { var e = b.length, f = this._map, c = f.charAt(64); c && (c = b.indexOf(c), -1 != c && (e = c)); for (var c = [], a = 0, d = 0; d < e; d++) if (d % 4) { var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4), h = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4); c[a >>> 2] |= (g | h) << 24 - 8 * (a % 4); a++ } return j.create(c, a) }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" } })(); + +hawk.crypto.internals = CryptoJS;