push all website files

This commit is contained in:
Jacob Levine
2019-01-06 13:14:45 -06:00
parent d7301e26c3
commit d2d5d4c04e
15662 changed files with 2166516 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
.tmp
coverage
.vscode
.idea
tsconfig.*
tslint.*
.travis.yml
.github
# Don't include the raw typescript
src
spec
integration_test
# TODO(rjh) add back once testing isn't just a joke
testing
lib/testing.*
*.tgz

View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "es5"
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Firebase
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,36 @@
# Firebase SDK for Cloud Functions
The `firebase-functions` package provides an SDK for defining Cloud Functions for Firebase.
Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. The Firebase SDK for Cloud Functions integrates the Firebase platform by letting you write code that responds to events and invokes functionality exposed by other Firebase features.
## Learn more
Learn more about the Firebase SDK for Cloud Functions in the [Firebase documentation](https://firebase.google.com/docs/functions/) or [check out our samples](https://github.com/firebase/functions-samples).
## Migrating to v1
To migrate from a beta version of firebase-functions to v1, please refer to the [migration guide](https://firebase.google.com/docs/functions/beta-v1-diff).
## Usage
```js
// functions/index.js
const functions = require('firebase-functions');
const notifyUsers = require('./notify-users');
exports.newPost = functions.database
.ref('/posts/{postId}')
.onCreate((snapshot, context) => {
console.log('Received new post with ID:', context.params.postId);
return notifyUsers(snapshot.val());
});
```
## Contributing
To contribute a change, [check out the contributing guide](.github/CONTRIBUTING.md).
## License
© Google, 2017. Licensed under [The MIT License](LICENSE).

View File

@@ -0,0 +1 @@
feature - Added support for Remote Config triggered functions with `functions.remoteConfig`.

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,103 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const firebase = require("firebase-admin");
const config_1 = require("./config");
/** @internal */
function apps() {
if (typeof apps.singleton === 'undefined') {
apps.init();
}
return apps.singleton;
}
exports.apps = apps;
/** @internal */
(function (apps) {
/** @internal */
apps.garbageCollectionInterval = 2 * 60 * 1000;
/** @internal */
function delay(delay) {
return new Promise(resolve => {
setTimeout(resolve, delay);
});
}
apps.delay = delay;
apps.init = () => (apps.singleton = new Apps());
/** @internal */
class Apps {
constructor() {
this._refCounter = {};
}
_appAlive(appName) {
try {
let app = firebase.app(appName);
return !_.get(app, 'isDeleted_');
}
catch (e) {
return false;
}
}
_destroyApp(appName) {
if (!this._appAlive(appName)) {
return;
}
firebase
.app(appName)
.delete()
.catch(_.noop);
}
retain() {
let increment = (n) => {
return (n || 0) + 1;
};
// Increment counter for admin because function might use event.data.ref
_.update(this._refCounter, '__admin__', increment);
}
release() {
let decrement = (n) => {
return n - 1;
};
return delay(apps.garbageCollectionInterval).then(() => {
_.update(this._refCounter, '__admin__', decrement);
_.forEach(this._refCounter, (count, key) => {
if (count <= 0) {
this._destroyApp(key);
}
});
});
}
get admin() {
if (this._appAlive('__admin__')) {
return firebase.app('__admin__');
}
return firebase.initializeApp(this.firebaseArgs, '__admin__');
}
get firebaseArgs() {
return _.assign({}, config_1.firebaseConfig(), {
credential: firebase.credential.applicationDefault(),
});
}
}
apps.Apps = Apps;
})(apps = exports.apps || (exports.apps = {}));

View File

@@ -0,0 +1,107 @@
/// <reference types="express" />
import { Request, Response } from 'express';
import { DeploymentOptions } from './function-builder';
export { Request, Response };
/** The context in which an event occurred.
* An EventContext describes:
* - The time an event occurred.
* - A unique identifier of the event.
* - The resource on which the event occurred, if applicable.
* - Authorization of the request that triggered the event, if applicable and available.
*/
export interface EventContext {
/** ID of the event */
eventId: string;
/** Timestamp for when the event occured (ISO string) */
timestamp: string;
/** Type of event */
eventType: string;
/** Resource that triggered the event */
resource: Resource;
/** Key-value pairs that represent the values of wildcards in a database reference */
params: {
[option: string]: any;
};
/** Type of authentication for the triggering action, valid value are: 'ADMIN', 'USER',
* 'UNAUTHENTICATED'. Only available for database functions.
*/
authType?: 'ADMIN' | 'USER' | 'UNAUTHENTICATED';
/** Firebase auth variable for the user whose action triggered the function. Field will be
* null for unauthenticated users, and will not exist for admin users. Only available
* for database functions.
*/
auth?: {
uid: string;
token: object;
};
}
/** Change describes a change of state - "before" represents the state prior
* to the event, "after" represents the state after the event.
*/
export declare class Change<T> {
before: T;
after: T;
constructor(before?: T, after?: T);
}
/** ChangeJson is the JSON format used to construct a Change object. */
export interface ChangeJson {
/** Key-value pairs representing state of data before the change.
* If `fieldMask` is set, then only fields that changed are present in `before`.
*/
before?: any;
/** Key-value pairs representing state of data after the change. */
after?: any;
/** Comma-separated string that represents names of field that changed. */
fieldMask?: string;
}
export declare namespace Change {
/** Factory method for creating a Change from a `before` object and an `after` object. */
function fromObjects<T>(before: T, after: T): Change<T>;
/** Factory method for creating a Change from a JSON and an optional customizer function to be
* applied to both the `before` and the `after` fields.
*/
function fromJSON<T>(json: ChangeJson, customizer?: (x: any) => T): Change<T>;
}
/** Resource is a standard format for defining a resource (google.rpc.context.AttributeContext.Resource).
* In Cloud Functions, it is the resource that triggered the function - such as a storage bucket.
*/
export interface Resource {
service: string;
name: string;
type?: string;
labels?: {
[tag: string]: string;
};
}
/** TriggerAnnotated is used internally by the firebase CLI to understand what type of Cloud Function to deploy. */
export interface TriggerAnnotated {
__trigger: {
httpsTrigger?: {};
eventTrigger?: {
eventType: string;
resource: string;
service: string;
};
labels?: {
[key: string]: string;
};
regions?: string[];
timeout?: string;
availableMemoryMb?: number;
};
}
/** A Runnable has a `run` method which directly invokes the user-defined function - useful for unit testing. */
export interface Runnable<T> {
run: (data: T, context: any) => PromiseLike<any> | any;
}
/**
* An HttpsFunction is both an object that exports its trigger definitions at __trigger and
* can be called as a function that takes an express.js Request and Response object.
*/
export declare type HttpsFunction = TriggerAnnotated & ((req: Request, resp: Response) => void);
/**
* A CloudFunction is both an object that exports its trigger definitions at __trigger and
* can be called as a function using the raw JS API for Google Cloud Functions.
*/
export declare type CloudFunction<T> = Runnable<T> & TriggerAnnotated & ((input: any, context?: any) => PromiseLike<any> | any);
export declare function optsToTrigger(opts: DeploymentOptions): any;

View File

@@ -0,0 +1,218 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const WILDCARD_REGEX = new RegExp('{[^/{}]*}', 'g');
/** Change describes a change of state - "before" represents the state prior
* to the event, "after" represents the state after the event.
*/
class Change {
constructor(before, after) {
this.before = before;
this.after = after;
}
}
exports.Change = Change;
(function (Change) {
function reinterpretCast(x) {
return x;
}
/** Factory method for creating a Change from a `before` object and an `after` object. */
function fromObjects(before, after) {
return new Change(before, after);
}
Change.fromObjects = fromObjects;
/** Factory method for creating a Change from a JSON and an optional customizer function to be
* applied to both the `before` and the `after` fields.
*/
function fromJSON(json, customizer = reinterpretCast) {
let before = _.assign({}, json.before);
if (json.fieldMask) {
before = applyFieldMask(before, json.after, json.fieldMask);
}
return Change.fromObjects(customizer(before || {}), customizer(json.after || {}));
}
Change.fromJSON = fromJSON;
/** @internal */
function applyFieldMask(sparseBefore, after, fieldMask) {
let before = _.assign({}, after);
let masks = fieldMask.split(',');
_.forEach(masks, mask => {
const val = _.get(sparseBefore, mask);
if (typeof val === 'undefined') {
_.unset(before, mask);
}
else {
_.set(before, mask, val);
}
});
return before;
}
Change.applyFieldMask = applyFieldMask;
})(Change = exports.Change || (exports.Change = {}));
/** @internal */
function makeCloudFunction({ provider, eventType, triggerResource, service, dataConstructor = (raw) => raw.data, handler, before = () => {
return;
}, after = () => {
return;
}, legacyEventType, opts = {}, }) {
let cloudFunction;
let cloudFunctionNewSignature = (data, context) => {
if (legacyEventType && context.eventType === legacyEventType) {
// v1beta1 event flow has different format for context, transform them to new format.
context.eventType = provider + '.' + eventType;
context.resource = {
service: service,
name: context.resource,
};
}
let event = {
data,
context,
};
if (provider === 'google.firebase.database') {
context.authType = _detectAuthType(event);
if (context.authType !== 'ADMIN') {
context.auth = _makeAuth(event, context.authType);
}
else {
delete context.auth;
}
}
context.params = context.params || _makeParams(context, triggerResource);
before(event);
let dataOrChange = dataConstructor(event);
let promise = handler(dataOrChange, context);
if (typeof promise === 'undefined') {
console.warn('Function returned undefined, expected Promise or value');
}
return Promise.resolve(promise)
.then(result => {
after(event);
return result;
})
.catch(err => {
after(event);
return Promise.reject(err);
});
};
if (process.env.X_GOOGLE_NEW_FUNCTION_SIGNATURE === 'true') {
cloudFunction = cloudFunctionNewSignature;
}
else {
cloudFunction = (raw) => {
let context;
// In Node 6 runtime, function called with single event param
let data = _.get(raw, 'data');
if (isEvent(raw)) {
// new eventflow v1beta2 format
context = _.cloneDeep(raw.context);
}
else {
// eventflow v1beta1 format
context = _.omit(raw, 'data');
}
return cloudFunctionNewSignature(data, context);
};
}
Object.defineProperty(cloudFunction, '__trigger', {
get: () => {
let trigger = _.assign(optsToTrigger(opts), {
eventTrigger: {
resource: triggerResource(),
eventType: legacyEventType || provider + '.' + eventType,
service,
},
});
return trigger;
},
});
cloudFunction.run = handler;
return cloudFunction;
}
exports.makeCloudFunction = makeCloudFunction;
function isEvent(event) {
return _.has(event, 'context');
}
function _makeParams(context, triggerResourceGetter) {
if (context.params) {
// In unit testing, user may directly provide `context.params`.
return context.params;
}
if (!context.resource) {
// In unit testing, `resource` may be unpopulated for a test event.
return {};
}
let triggerResource = triggerResourceGetter();
let wildcards = triggerResource.match(WILDCARD_REGEX);
let params = {};
if (wildcards) {
let triggerResourceParts = _.split(triggerResource, '/');
let eventResourceParts = _.split(context.resource.name, '/');
_.forEach(wildcards, wildcard => {
let wildcardNoBraces = wildcard.slice(1, -1);
let position = _.indexOf(triggerResourceParts, wildcard);
params[wildcardNoBraces] = eventResourceParts[position];
});
}
return params;
}
function _makeAuth(event, authType) {
if (authType === 'UNAUTHENTICATED') {
return null;
}
return {
uid: _.get(event, 'context.auth.variable.uid'),
token: _.get(event, 'context.auth.variable.token'),
};
}
function _detectAuthType(event) {
if (_.get(event, 'context.auth.admin')) {
return 'ADMIN';
}
if (_.has(event, 'context.auth.variable')) {
return 'USER';
}
return 'UNAUTHENTICATED';
}
function optsToTrigger(opts) {
let trigger = {};
if (opts.regions) {
trigger.regions = opts.regions;
}
if (opts.timeoutSeconds) {
trigger.timeout = opts.timeoutSeconds.toString() + 's';
}
if (opts.memory) {
const memoryLookup = {
'128MB': 128,
'256MB': 256,
'512MB': 512,
'1GB': 1024,
'2GB': 2048,
};
trigger.availableMemoryMb = _.get(memoryLookup, opts.memory);
}
return trigger;
}
exports.optsToTrigger = optsToTrigger;

View File

@@ -0,0 +1,6 @@
export declare function config(): config.Config;
export declare namespace config {
type Config = {
[key: string]: any;
};
}

View File

@@ -0,0 +1,87 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
function config() {
if (typeof config.singleton === 'undefined') {
init();
}
return config.singleton;
}
exports.config = config;
(function (config) {
})(config = exports.config || (exports.config = {}));
/* @internal */
function firebaseConfig() {
// The FIREBASE_PROJECT environment variable was introduced to help local emulation with `firebase-tools` 3.18
// Unfortunately, API review decided that the name should be FIREBASE_CONFIG to avoid confusions that Firebase has
// a separate project from Google Cloud. This accepts both versions, preferring the documented name.
const env = process.env.FIREBASE_CONFIG || process.env.FIREBASE_PROJECT;
if (env) {
return JSON.parse(env);
}
// Could have Runtime Config with Firebase in it as an ENV value.
try {
const config = JSON.parse(process.env.CLOUD_RUNTIME_CONFIG);
if (config.firebase) {
return config.firebase;
}
}
catch (e) {
// Do nothing
}
// Could have Runtime Config with Firebase in it as an ENV location or default.
try {
const path = process.env.CLOUD_RUNTIME_CONFIG || '../../../.runtimeconfig.json';
const config = require(path);
if (config.firebase) {
return config.firebase;
}
}
catch (e) {
// Do nothing
}
return null;
}
exports.firebaseConfig = firebaseConfig;
function init() {
try {
const parsed = JSON.parse(process.env.CLOUD_RUNTIME_CONFIG);
delete parsed.firebase;
config.singleton = parsed;
return;
}
catch (e) {
// Do nothing
}
try {
let path = process.env.CLOUD_RUNTIME_CONFIG || '../../../.runtimeconfig.json';
const parsed = require(path);
delete parsed.firebase;
config.singleton = parsed;
return;
}
catch (e) {
// Do nothing
}
config.singleton = {};
}

View File

@@ -0,0 +1,4 @@
export declare function dateToTimestampProto(timeString?: string): {
seconds: number;
nanos: number;
};

View File

@@ -0,0 +1,38 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
function dateToTimestampProto(timeString) {
if (typeof timeString === 'undefined') {
return;
}
let date = new Date(timeString);
let seconds = Math.floor(date.getTime() / 1000);
let nanos = 0;
if (timeString.length > 20) {
const nanoString = timeString.substring(20, timeString.length - 1);
const trailingZeroes = 9 - nanoString.length;
nanos = parseInt(nanoString, 10) * Math.pow(10, trailingZeroes);
}
return { seconds, nanos };
}
exports.dateToTimestampProto = dateToTimestampProto;

View File

@@ -0,0 +1,87 @@
/// <reference types="express" />
import * as express from 'express';
import * as analytics from './providers/analytics';
import * as auth from './providers/auth';
import * as crashlytics from './providers/crashlytics';
import * as database from './providers/database';
import * as firestore from './providers/firestore';
import * as https from './providers/https';
import * as pubsub from './providers/pubsub';
import * as remoteConfig from './providers/remoteConfig';
import * as storage from './providers/storage';
import { CloudFunction, EventContext, HttpsFunction } from './cloud-functions';
/**
* Configure the regions that the function is deployed to.
* @param region Region string.
* For example: `functions.region('us-east1')`
*/
export declare function region(region: string): FunctionBuilder;
/**
* Configure runtime options for the function.
* @param runtimeOptions Object with 2 optional fields:
* 1. `timeoutSeconds`: timeout for the function in seconds.
* 2. `memory`: amount of memory to allocate to the function,
* possible values are: '128MB', '256MB', '512MB', '1GB', and '2GB'.
*/
export declare function runWith(runtimeOptions: {
timeoutSeconds?: number;
memory?: '128MB' | '256MB' | '512MB' | '1GB' | '2GB';
}): FunctionBuilder;
export interface DeploymentOptions {
regions?: string[];
timeoutSeconds?: number;
memory?: string;
}
export declare class FunctionBuilder {
private options;
constructor(options: DeploymentOptions);
/**
* Configure the regions that the function is deployed to.
* @param region Region string.
* For example: `functions.region('us-east1')`
*/
region: (region: string) => this;
/**
* Configure runtime options for the function.
* @param runtimeOptions Object with 2 optional fields:
* 1. timeoutSeconds: timeout for the function in seconds.
* 2. memory: amount of memory to allocate to the function, possible values are:
* '128MB', '256MB', '512MB', '1GB', and '2GB'.
*/
runWith: (runtimeOptions: {
timeoutSeconds?: number;
memory?: "128MB" | "256MB" | "512MB" | "1GB" | "2GB";
}) => this;
readonly https: {
onRequest: (handler: (req: express.Request, resp: express.Response) => void) => HttpsFunction;
onCall: (handler: (data: any, context: https.CallableContext) => any) => HttpsFunction;
};
readonly database: {
instance: (instance: string) => database.InstanceBuilder;
ref: (path: string) => database.RefBuilder;
};
readonly firestore: {
document: (path: string) => firestore.DocumentBuilder;
namespace: (namespace: string) => firestore.NamespaceBuilder;
database: (database: string) => firestore.DatabaseBuilder;
};
readonly crashlytics: {
issue: () => crashlytics.IssueBuilder;
};
readonly analytics: {
event: (analyticsEventType: string) => analytics.AnalyticsEventBuilder;
};
readonly remoteConfig: {
onUpdate: (handler: (version: remoteConfig.TemplateVersion, context: EventContext) => any) => CloudFunction<remoteConfig.TemplateVersion>;
};
readonly storage: {
bucket: (bucket?: string) => storage.BucketBuilder;
object: () => storage.ObjectBuilder;
};
readonly pubsub: {
topic: (topic: string) => pubsub.TopicBuilder;
};
readonly auth: {
user: () => auth.UserBuilder;
};
}

View File

@@ -0,0 +1,212 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const analytics = require("./providers/analytics");
const auth = require("./providers/auth");
const crashlytics = require("./providers/crashlytics");
const database = require("./providers/database");
const firestore = require("./providers/firestore");
const https = require("./providers/https");
const pubsub = require("./providers/pubsub");
const remoteConfig = require("./providers/remoteConfig");
const storage = require("./providers/storage");
/**
* Configure the regions that the function is deployed to.
* @param region Region string.
* For example: `functions.region('us-east1')`
*/
function region(region) {
return new FunctionBuilder({ regions: [region] });
}
exports.region = region;
/**
* Configure runtime options for the function.
* @param runtimeOptions Object with 2 optional fields:
* 1. `timeoutSeconds`: timeout for the function in seconds.
* 2. `memory`: amount of memory to allocate to the function,
* possible values are: '128MB', '256MB', '512MB', '1GB', and '2GB'.
*/
function runWith(runtimeOptions) {
if (runtimeOptions.memory &&
!_.includes(['128MB', '256MB', '512MB', '1GB', '2GB'], runtimeOptions.memory)) {
throw new Error("The only valid memory allocation values are: '128MB', '256MB', '512MB', '1GB', and '2GB'");
}
return new FunctionBuilder(runtimeOptions);
}
exports.runWith = runWith;
class FunctionBuilder {
constructor(options) {
this.options = options;
/**
* Configure the regions that the function is deployed to.
* @param region Region string.
* For example: `functions.region('us-east1')`
*/
this.region = (region) => {
this.options.regions = [region];
return this;
};
/**
* Configure runtime options for the function.
* @param runtimeOptions Object with 2 optional fields:
* 1. timeoutSeconds: timeout for the function in seconds.
* 2. memory: amount of memory to allocate to the function, possible values are:
* '128MB', '256MB', '512MB', '1GB', and '2GB'.
*/
this.runWith = (runtimeOptions) => {
if (runtimeOptions.memory &&
!_.includes(['128MB', '256MB', '512MB', '1GB', '2GB'], runtimeOptions.memory)) {
throw new Error("The only valid memory allocation values are: '128MB', '256MB', '512MB', '1GB', and '2GB'");
}
this.options = _.assign(this.options, runtimeOptions);
return this;
};
}
get https() {
return {
/**
* Handle HTTP requests.
* @param handler A function that takes a request and response object,
* same signature as an Express app.
*/
onRequest: (handler) => https._onRequestWithOpts(handler, this.options),
/**
* Declares a callable method for clients to call using a Firebase SDK.
* @param handler A method that takes a data and context and returns a value.
*/
onCall: (handler) => https._onCallWithOpts(handler, this.options),
};
}
get database() {
return {
/**
* Selects a database instance that will trigger the function.
* If omitted, will pick the default database for your project.
* @param instance The Realtime Database instance to use.
*/
instance: (instance) => database._instanceWithOpts(instance, this.options),
/**
* Select Firebase Realtime Database Reference to listen to.
*
* This method behaves very similarly to the method of the same name in the
* client and Admin Firebase SDKs. Any change to the Database that affects the
* data at or below the provided `path` will fire an event in Cloud Functions.
*
* There are three important differences between listening to a Realtime
* Database event in Cloud Functions and using the Realtime Database in the
* client and Admin SDKs:
* 1. Cloud Functions allows wildcards in the `path` name. Any `path` component
* in curly brackets (`{}`) is a wildcard that matches all strings. The value
* that matched a certain invocation of a Cloud Function is returned as part
* of the `context.params` object. For example, `ref("messages/{messageId}")`
* matches changes at `/messages/message1` or `/messages/message2`, resulting
* in `context.params.messageId` being set to `"message1"` or `"message2"`,
* respectively.
* 2. Cloud Functions do not fire an event for data that already existed before
* the Cloud Function was deployed.
* 3. Cloud Function events have access to more information, including information
* about the user who triggered the Cloud Function.
* @param ref Path of the database to listen to.
*/
ref: (path) => database._refWithOpts(path, this.options),
};
}
get firestore() {
return {
/**
* Select the Firestore document to listen to for events.
* @param path Full database path to listen to. This includes the name of
* the collection that the document is a part of. For example, if the
* collection is named "users" and the document is named "Ada", then the
* path is "/users/Ada".
*/
document: (path) => firestore._documentWithOpts(path, this.options),
/** @internal */
namespace: (namespace) => firestore._namespaceWithOpts(namespace, this.options),
/** @internal */
database: (database) => firestore._databaseWithOpts(database, this.options),
};
}
get crashlytics() {
return {
/**
* Handle events related to Crashlytics issues. An issue in Crashlytics is an
* aggregation of crashes which have a shared root cause.
*/
issue: () => crashlytics._issueWithOpts(this.options),
};
}
get analytics() {
return {
/**
* Select analytics events to listen to for events.
* @param analyticsEventType Name of the analytics event type.
*/
event: (analyticsEventType) => analytics._eventWithOpts(analyticsEventType, this.options),
};
}
get remoteConfig() {
return {
/**
* Handle all updates (including rollbacks) that affect a Remote Config
* project.
* @param handler A function that takes the updated Remote Config template
* version metadata as an argument.
*/
onUpdate: (handler) => remoteConfig._onUpdateWithOpts(handler, this.options),
};
}
get storage() {
return {
/**
* The optional bucket function allows you to choose which buckets' events to handle.
* This step can be bypassed by calling object() directly, which will use the default
* Cloud Storage for Firebase bucket.
* @param bucket Name of the Google Cloud Storage bucket to listen to.
*/
bucket: (bucket) => storage._bucketWithOpts(this.options, bucket),
/**
* Handle events related to Cloud Storage objects.
*/
object: () => storage._objectWithOpts(this.options),
};
}
get pubsub() {
return {
/** Select Cloud Pub/Sub topic to listen to.
* @param topic Name of Pub/Sub topic, must belong to the same project as the function.
*/
topic: (topic) => pubsub._topicWithOpts(topic, this.options),
};
}
get auth() {
return {
/**
* Handle events related to Firebase authentication users.
*/
user: () => auth._userWithOpts(this.options),
};
}
}
exports.FunctionBuilder = FunctionBuilder;

View File

@@ -0,0 +1,13 @@
import * as analytics from './providers/analytics';
import * as auth from './providers/auth';
import * as crashlytics from './providers/crashlytics';
import * as database from './providers/database';
import * as firestore from './providers/firestore';
import * as https from './providers/https';
import * as pubsub from './providers/pubsub';
import * as remoteConfig from './providers/remoteConfig';
import * as storage from './providers/storage';
export { analytics, auth, crashlytics, database, firestore, https, pubsub, remoteConfig, storage };
export * from './config';
export * from './cloud-functions';
export * from './function-builder';

View File

@@ -0,0 +1,70 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
// Providers:
const analytics = require("./providers/analytics");
exports.analytics = analytics;
const auth = require("./providers/auth");
exports.auth = auth;
const crashlytics = require("./providers/crashlytics");
exports.crashlytics = crashlytics;
const database = require("./providers/database");
exports.database = database;
const firestore = require("./providers/firestore");
exports.firestore = firestore;
const https = require("./providers/https");
exports.https = https;
const pubsub = require("./providers/pubsub");
exports.pubsub = pubsub;
const remoteConfig = require("./providers/remoteConfig");
exports.remoteConfig = remoteConfig;
const storage = require("./providers/storage");
exports.storage = storage;
const config_1 = require("./config");
// // Exported root types:
__export(require("./config"));
__export(require("./cloud-functions"));
__export(require("./function-builder"));
// TEMPORARY WORKAROUND (BUG 63586213):
// Until the Cloud Functions builder can publish FIREBASE_CONFIG, automatically provide it on import based on what
// we can deduce.
if (!process.env.FIREBASE_CONFIG) {
const cfg = config_1.firebaseConfig();
if (cfg) {
process.env.FIREBASE_CONFIG = JSON.stringify(cfg);
}
else if (process.env.GCLOUD_PROJECT) {
console.warn('Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail');
process.env.FIREBASE_CONFIG = JSON.stringify({
databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
storageBucket: `${process.env.GCLOUD_PROJECT}.appspot.com`,
projectId: process.env.GCLOUD_PROJECT,
});
}
else {
console.warn('Warning, FIREBASE_CONFIG environment variable is missing. Initializing firebase-admin will fail');
}
}

View File

@@ -0,0 +1,206 @@
import { CloudFunction, EventContext } from '../cloud-functions';
/**
* Select analytics events to listen to for events.
* @param analyticsEventType Name of the analytics event type.
*/
export declare function event(analyticsEventType: string): AnalyticsEventBuilder;
/**
* The Firebase Analytics event builder interface.
*
* Access via [`functions.analytics.event()`](functions.analytics#event).
*/
export declare class AnalyticsEventBuilder {
private triggerResource;
private opts;
/**
* Event handler that fires every time a Firebase Analytics event occurs.
*
* @param {!function(!functions.Event<!functions.analytics.AnalyticsEvent>)}
* handler Event handler that fires every time a Firebase Analytics event
* occurs.
*
* @return {!functions.CloudFunction<!functions.analytics.AnalyticsEvent>} A
* Cloud Function you can export.
*/
onLog(handler: (event: AnalyticsEvent, context: EventContext) => PromiseLike<any> | any): CloudFunction<AnalyticsEvent>;
}
/**
* Interface representing a Firebase Analytics event that was logged for a specific user.
*/
export declare class AnalyticsEvent {
/**
* The date on which the event.was logged.
* (`YYYYMMDD` format in the registered timezone of your app).
*/
reportingDate: string;
/** The name of the event. */
name: string;
/**
* A map of parameters and their values associated with the event.
*
* Note: Values in this map are cast to the most appropriate type. Due to
* the nature of JavaScript's number handling, this might entail a loss of
* precision in cases of very large integers.
*/
params: {
[key: string]: any;
};
/** UTC client time when the event happened. */
logTime: string;
/** UTC client time when the previous event happened. */
previousLogTime?: string;
/** Value parameter in USD. */
valueInUSD?: number;
/** User-related dimensions. */
user?: UserDimensions;
}
/**
* Interface representing the user who triggered the events.
*/
export declare class UserDimensions {
/**
* The user ID set via the `setUserId` API.
* [Android](https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.html#setUserId(java.lang.String))
* [iOS](https://firebase.google.com/docs/reference/ios/firebaseanalytics/api/reference/Classes/FIRAnalytics#/c:objc(cs)FIRAnalytics(cm)setUserID)
*/
userId?: string;
/** The time (in UTC) at which the user first opened the app. */
firstOpenTime?: string;
/**
* A map of user properties set with the
* [`setUserProperty`](https://firebase.google.com/docs/analytics/android/properties) API.
*
* All values are [`UserPropertyValue`](functions.analytics.UserPropertyValue) objects.
*/
userProperties: {
[key: string]: UserPropertyValue;
};
/** Device information. */
deviceInfo: DeviceInfo;
/** User's geographic information. */
geoInfo: GeoInfo;
/** App information. */
appInfo?: AppInfo;
/** Information regarding the bundle in which these events were uploaded. */
bundleInfo: ExportBundleInfo;
}
/**
* Predefined or custom properties stored on the client side.
*/
export declare class UserPropertyValue {
/** Last set value of a user property. */
value: string;
/** UTC client time when the user property was last set. */
setTime: string;
}
/**
* Interface representing the device that triggered these Firebase Analytics events.
*/
export interface DeviceInfo {
/**
* Device category.
* Examples: "tablet" or "mobile".
*/
deviceCategory?: string;
/**
* Device brand name.
* Examples: "Samsung", "HTC"
*/
mobileBrandName?: string;
/**
* Device model name in human-readable format.
* Example: "iPhone 7"
*/
mobileModelName?: string;
/**
* Device marketing name.
* Example: "Galaxy S4 Mini"
*/
mobileMarketingName?: string;
/**
* Device model, as read from the OS.
* Example: "iPhone9,1"
*/
deviceModel?: string;
/**
* Device OS version when data capture ended.
* Example: "4.4.2"
*/
platformVersion?: string;
/**
* Vendor specific device identifier. This is IDFV on iOS. Not used for Android.
* Example: '599F9C00-92DC-4B5C-9464-7971F01F8370'
*/
deviceId?: string;
/**
* The type of the [`resettable_device_id`](https://support.google.com/dfp_premium/answer/6238701?hl=en)
* is IDFA on iOS (when available) and AdId on Android.
*
* Example: "71683BF9-FA3B-4B0D-9535-A1F05188BAF3"
*/
resettableDeviceId?: string;
/**
* The user language in language-country format, where language is an ISO 639
* value and country is an ISO 3166 value.
*
* Examples: "en-us", "en-za", "zh-tw", "jp"
*/
userDefaultLanguage: string;
/**
* The time zone of the device when data was uploaded, as seconds skew from UTC.
* Use this to calculate the device's local time for [`event.timestamp`](functions.Event#timestamp)`.
*/
deviceTimeZoneOffsetSeconds: number;
/**
* The device's Limit Ad Tracking setting.
* When `true`, you cannot use `resettableDeviceId` for remarketing, demographics or influencing ads serving
* behaviour. However, you can use resettableDeviceId for conversion tracking and campaign attribution.
*/
limitedAdTracking: boolean;
}
/**
* Interface representing the geographic origin of the events.
*/
export interface GeoInfo {
/** The geographic continent. Example: "Americas". */
continent?: string;
/** The geographic country. Example: "Brazil". */
country?: string;
/** The geographic region. Example: "State of Sao Paulo". */
region?: string;
/** The geographic city. Example: "Sao Paulo". */
city?: string;
}
/**
* Interface representing the application that triggered these events.
*/
export interface AppInfo {
/**
* The app's version name.
* Examples: "1.0", "4.3.1.1.213361", "2.3 (1824253)", "v1.8b22p6".
*/
appVersion?: string;
/**
* Unique id for this instance of the app.
* Example: "71683BF9FA3B4B0D9535A1F05188BAF3".
*/
appInstanceId: string;
/**
* The identifier of the store that installed the app.
* Examples: "com.sec.android.app.samsungapps", "com.amazon.venezia", "com.nokia.nstore".
*/
appStore?: string;
/** The app platform. Examples: "ANDROID", "IOS". */
appPlatform: string;
/** Unique application identifier within an app store. */
appId?: string;
}
/**
* Interface representing the bundle in which these events were uploaded.
*/
export declare class ExportBundleInfo {
/** Monotonically increasing index for each bundle set by the Analytics SDK. */
bundleSequenceId: number;
/** Timestamp offset (in milliseconds) between collection time and upload time. */
serverTimestampOffset: number;
}

View File

@@ -0,0 +1,236 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const cloud_functions_1 = require("../cloud-functions");
/** @internal */
exports.provider = 'google.analytics';
/** @internal */
exports.service = 'app-measurement.com';
/**
* Select analytics events to listen to for events.
* @param analyticsEventType Name of the analytics event type.
*/
function event(analyticsEventType) {
return _eventWithOpts(analyticsEventType, {});
}
exports.event = event;
/** @internal */
function _eventWithOpts(analyticsEventType, opts) {
return new AnalyticsEventBuilder(() => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error('process.env.GCLOUD_PROJECT is not set.');
}
return ('projects/' + process.env.GCLOUD_PROJECT + '/events/' + analyticsEventType);
}, opts);
}
exports._eventWithOpts = _eventWithOpts;
/**
* The Firebase Analytics event builder interface.
*
* Access via [`functions.analytics.event()`](functions.analytics#event).
*/
class AnalyticsEventBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
}
/**
* Event handler that fires every time a Firebase Analytics event occurs.
*
* @param {!function(!functions.Event<!functions.analytics.AnalyticsEvent>)}
* handler Event handler that fires every time a Firebase Analytics event
* occurs.
*
* @return {!functions.CloudFunction<!functions.analytics.AnalyticsEvent>} A
* Cloud Function you can export.
*/
onLog(handler) {
const dataConstructor = (raw) => {
return new AnalyticsEvent(raw.data);
};
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
eventType: 'event.log',
service: exports.service,
legacyEventType: `providers/google.firebase.analytics/eventTypes/event.log`,
triggerResource: this.triggerResource,
dataConstructor,
opts: this.opts,
});
}
}
exports.AnalyticsEventBuilder = AnalyticsEventBuilder;
/**
* Interface representing a Firebase Analytics event that was logged for a specific user.
*/
class AnalyticsEvent {
/** @internal */
constructor(wireFormat) {
this.params = {}; // In case of absent field, show empty (not absent) map.
if (wireFormat.eventDim && wireFormat.eventDim.length > 0) {
// If there's an eventDim, there'll always be exactly one.
let eventDim = wireFormat.eventDim[0];
copyField(eventDim, this, 'name');
copyField(eventDim, this, 'params', p => _.mapValues(p, unwrapValue));
copyFieldTo(eventDim, this, 'valueInUsd', 'valueInUSD');
copyFieldTo(eventDim, this, 'date', 'reportingDate');
copyTimestampToString(eventDim, this, 'timestampMicros', 'logTime');
copyTimestampToString(eventDim, this, 'previousTimestampMicros', 'previousLogTime');
}
copyFieldTo(wireFormat, this, 'userDim', 'user', dim => new UserDimensions(dim));
}
}
exports.AnalyticsEvent = AnalyticsEvent;
/**
* Interface representing the user who triggered the events.
*/
class UserDimensions {
/** @internal */
constructor(wireFormat) {
// These are interfaces or primitives, no transformation needed.
copyFields(wireFormat, this, [
'userId',
'deviceInfo',
'geoInfo',
'appInfo',
]);
// The following fields do need transformations of some sort.
copyTimestampToString(wireFormat, this, 'firstOpenTimestampMicros', 'firstOpenTime');
this.userProperties = {}; // With no entries in the wire format, present an empty (as opposed to absent) map.
copyField(wireFormat, this, 'userProperties', r => _.mapValues(r, p => new UserPropertyValue(p)));
copyField(wireFormat, this, 'bundleInfo', r => new ExportBundleInfo(r));
// BUG(36000368) Remove when no longer necessary
/* tslint:disable:no-string-literal */
if (!this.userId && this.userProperties['user_id']) {
this.userId = this.userProperties['user_id'].value;
}
/* tslint:enable:no-string-literal */
}
}
exports.UserDimensions = UserDimensions;
/**
* Predefined or custom properties stored on the client side.
*/
class UserPropertyValue {
/** @internal */
constructor(wireFormat) {
copyField(wireFormat, this, 'value', unwrapValueAsString);
copyTimestampToString(wireFormat, this, 'setTimestampUsec', 'setTime');
}
}
exports.UserPropertyValue = UserPropertyValue;
/**
* Interface representing the bundle in which these events were uploaded.
*/
class ExportBundleInfo {
/** @internal */
constructor(wireFormat) {
copyField(wireFormat, this, 'bundleSequenceId');
copyTimestampToMillis(wireFormat, this, 'serverTimestampOffsetMicros', 'serverTimestampOffset');
}
}
exports.ExportBundleInfo = ExportBundleInfo;
function copyFieldTo(from, to, fromField, toField, transform = _.identity) {
if (from[fromField] !== undefined) {
to[toField] = transform(from[fromField]);
}
}
function copyField(from, to, field, transform = _.identity) {
copyFieldTo(from, to, field, field, transform);
}
function copyFields(from, to, fields) {
for (let field of fields) {
copyField(from, to, field);
}
}
// The incoming payload will have fields like:
// {
// 'myInt': {
// 'intValue': '123'
// },
// 'myDouble': {
// 'doubleValue': 1.0
// },
// 'myFloat': {
// 'floatValue': 1.1
// },
// 'myString': {
// 'stringValue': 'hi!'
// }
// }
//
// The following method will remove these four types of 'xValue' fields, flattening them
// to just their values, as a string:
// {
// 'myInt': '123',
// 'myDouble': '1.0',
// 'myFloat': '1.1',
// 'myString': 'hi!'
// }
//
// Note that while 'intValue' will have a quoted payload, 'doubleValue' and 'floatValue' will not. This
// is due to the encoding library, which renders int64 values as strings to avoid loss of precision. This
// method always returns a string, similarly to avoid loss of precision, unlike the less-conservative
// 'unwrapValue' method just below.
function unwrapValueAsString(wrapped) {
let key = _.keys(wrapped)[0];
return _.toString(wrapped[key]);
}
// Ditto as the method above, but returning the values in the idiomatic JavaScript type (string for strings,
// number for numbers):
// {
// 'myInt': 123,
// 'myDouble': 1.0,
// 'myFloat': 1.1,
// 'myString': 'hi!'
// }
//
// The field names in the incoming xValue fields identify the type a value has, which for JavaScript's
// purposes can be divided into 'number' versus 'string'. This method will render all the numbers as
// JavaScript's 'number' type, since we prefer using idiomatic types. Note that this may lead to loss
// in precision for int64 fields, so use with care.
const xValueNumberFields = ['intValue', 'floatValue', 'doubleValue'];
function unwrapValue(wrapped) {
let key = _.keys(wrapped)[0];
let value = unwrapValueAsString(wrapped);
return _.includes(xValueNumberFields, key) ? _.toNumber(value) : value;
}
// The JSON payload delivers timestamp fields as strings of timestamps denoted in microseconds.
// The JavaScript convention is to use numbers denoted in milliseconds. This method
// makes it easy to convert a field of one type into the other.
function copyTimestampToMillis(from, to, fromName, toName) {
if (from[fromName] !== undefined) {
to[toName] = _.round(from[fromName] / 1000);
}
}
// The JSON payload delivers timestamp fields as strings of timestamps denoted in microseconds.
// In our SDK, we'd like to present timestamp as ISO-format strings. This method makes it easy
// to convert a field of one type into the other.
function copyTimestampToString(from, to, fromName, toName) {
if (from[fromName] !== undefined) {
to[toName] = new Date(from[fromName] / 1000).toISOString();
}
}

View File

@@ -0,0 +1,33 @@
import { CloudFunction, EventContext } from '../cloud-functions';
import * as firebase from 'firebase-admin';
/**
* Handle events related to Firebase authentication users.
*/
export declare function user(): UserBuilder;
export declare class UserRecordMetadata implements firebase.auth.UserMetadata {
creationTime: string;
lastSignInTime: string;
constructor(creationTime: string, lastSignInTime: string);
/** Returns a plain JavaScript object with the properties of UserRecordMetadata. */
toJSON(): {
creationTime: string;
lastSignInTime: string;
};
}
/** Builder used to create Cloud Functions for Firebase Auth user lifecycle events. */
export declare class UserBuilder {
private triggerResource;
private opts;
private static dataConstructor(raw);
/** Respond to the creation of a Firebase Auth user. */
onCreate(handler: (user: UserRecord, context: EventContext) => PromiseLike<any> | any): CloudFunction<UserRecord>;
/** Respond to the deletion of a Firebase Auth user. */
onDelete(handler: (user: UserRecord, context: EventContext) => PromiseLike<any> | any): CloudFunction<UserRecord>;
private onOperation(handler, eventType);
}
/**
* The UserRecord passed to Cloud Functions is the same UserRecord that is returned by the Firebase Admin
* SDK.
*/
export declare type UserRecord = firebase.auth.UserRecord;
export declare function userRecordConstructor(wireData: Object): firebase.auth.UserRecord;

View File

@@ -0,0 +1,143 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const cloud_functions_1 = require("../cloud-functions");
const _ = require("lodash");
/** @internal */
exports.provider = 'google.firebase.auth';
/** @internal */
exports.service = 'firebaseauth.googleapis.com';
/**
* Handle events related to Firebase authentication users.
*/
function user() {
return _userWithOpts({});
}
exports.user = user;
/** @internal */
function _userWithOpts(opts) {
return new UserBuilder(() => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error('process.env.GCLOUD_PROJECT is not set.');
}
return 'projects/' + process.env.GCLOUD_PROJECT;
}, opts);
}
exports._userWithOpts = _userWithOpts;
class UserRecordMetadata {
constructor(creationTime, lastSignInTime) {
this.creationTime = creationTime;
this.lastSignInTime = lastSignInTime;
}
/** Returns a plain JavaScript object with the properties of UserRecordMetadata. */
toJSON() {
return {
creationTime: this.creationTime,
lastSignInTime: this.lastSignInTime,
};
}
}
exports.UserRecordMetadata = UserRecordMetadata;
/** Builder used to create Cloud Functions for Firebase Auth user lifecycle events. */
class UserBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
}
static dataConstructor(raw) {
return userRecordConstructor(raw.data);
}
/** Respond to the creation of a Firebase Auth user. */
onCreate(handler) {
return this.onOperation(handler, 'user.create');
}
/** Respond to the deletion of a Firebase Auth user. */
onDelete(handler) {
return this.onOperation(handler, 'user.delete');
}
onOperation(handler, eventType) {
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
eventType,
service: exports.service,
triggerResource: this.triggerResource,
dataConstructor: UserBuilder.dataConstructor,
legacyEventType: `providers/firebase.auth/eventTypes/${eventType}`,
opts: this.opts,
});
}
}
exports.UserBuilder = UserBuilder;
function userRecordConstructor(wireData) {
// Falsey values from the wire format proto get lost when converted to JSON, this adds them back.
let falseyValues = {
email: null,
emailVerified: false,
displayName: null,
photoURL: null,
phoneNumber: null,
disabled: false,
providerData: [],
customClaims: {},
passwordSalt: null,
passwordHash: null,
tokensValidAfterTime: null,
};
let record = _.assign({}, falseyValues, wireData);
let meta = _.get(record, 'metadata');
if (meta) {
_.set(record, 'metadata', new UserRecordMetadata(
// Transform payload to firebase-admin v5.0.0 format because wire format is different (BUG 63167395)
meta.createdAt || meta.creationTime, meta.lastSignedInAt || meta.lastSignInTime));
}
else {
_.set(record, 'metadata', new UserRecordMetadata(null, null));
}
_.forEach(record.providerData, entry => {
_.set(entry, 'toJSON', () => {
return entry;
});
});
_.set(record, 'toJSON', () => {
const json = _.pick(record, [
'uid',
'email',
'emailVerified',
'displayName',
'photoURL',
'phoneNumber',
'disabled',
'passwordHash',
'passwordSalt',
'tokensValidAfterTime',
]);
json.metadata = _.get(record, 'metadata').toJSON();
json.customClaims = _.cloneDeep(record.customClaims);
json.providerData = _.map(record.providerData, entry => entry.toJSON());
return json;
});
return record;
}
exports.userRecordConstructor = userRecordConstructor;

View File

@@ -0,0 +1,57 @@
import { CloudFunction, EventContext } from '../cloud-functions';
/**
* Handle events related to Crashlytics issues. An issue in Crashlytics is an
* aggregation of crashes which have a shared root cause.
*/
export declare function issue(): IssueBuilder;
/** Builder used to create Cloud Functions for Crashlytics issue events. */
export declare class IssueBuilder {
private triggerResource;
private opts;
/** Handle Crashlytics New Issue events. */
onNew(handler: (issue: Issue, context: EventContext) => PromiseLike<any> | any): CloudFunction<Issue>;
/** Handle Crashlytics Regressed Issue events. */
onRegressed(handler: (issue: Issue, context: EventContext) => PromiseLike<any> | any): CloudFunction<Issue>;
/** Handle Crashlytics Velocity Alert events. */
onVelocityAlert(handler: (issue: Issue, context: EventContext) => PromiseLike<any> | any): CloudFunction<Issue>;
private onEvent(handler, eventType);
}
/**
* Interface representing a Crashlytics issue event that was logged for a specific issue.
*/
export interface Issue {
/** Fabric Issue ID. */
issueId: string;
/** Issue title. */
issueTitle: string;
/** App information. */
appInfo: AppInfo;
/** When the issue was created (ISO8601 time stamp). */
createTime: string;
/** When the issue was resolved, if the issue has been resolved (ISO8601 time stamp). */
resolvedTime?: string;
/** Contains details about the velocity alert, if this event was triggered by a velocity alert. */
velocityAlert?: VelocityAlert;
}
export interface VelocityAlert {
/** The percentage of sessions which have been impacted by this issue. Example: .04 */
crashPercentage: number;
/** The number of crashes that this issue has caused. */
crashes: number;
}
/**
* Interface representing the application where this issue occurred.
*/
export interface AppInfo {
/** The app's name. Example: "My Awesome App". */
appName: string;
/** The app's platform. Examples: "android", "ios". */
appPlatform: string;
/** Unique application identifier within an app store, either the Android package name or the iOS bundle id. */
appId: string;
/**
* The latest app version which is affected by the issue.
* Examples: "1.0", "4.3.1.1.213361", "2.3 (1824253)", "v1.8b22p6".
*/
latestAppVersion: string;
}

View File

@@ -0,0 +1,82 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const cloud_functions_1 = require("../cloud-functions");
/** @internal */
exports.provider = 'google.firebase.crashlytics';
/** @internal */
exports.service = 'fabric.io';
/**
* Handle events related to Crashlytics issues. An issue in Crashlytics is an
* aggregation of crashes which have a shared root cause.
*/
function issue() {
return _issueWithOpts({});
}
exports.issue = issue;
/** @internal */
function _issueWithOpts(opts) {
return new IssueBuilder(() => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error('process.env.GCLOUD_PROJECT is not set.');
}
return 'projects/' + process.env.GCLOUD_PROJECT;
}, opts);
}
exports._issueWithOpts = _issueWithOpts;
/** Builder used to create Cloud Functions for Crashlytics issue events. */
class IssueBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
}
/** @internal */
onNewDetected(handler) {
throw new Error('"onNewDetected" is now deprecated, please use "onNew"');
}
/** Handle Crashlytics New Issue events. */
onNew(handler) {
return this.onEvent(handler, 'issue.new');
}
/** Handle Crashlytics Regressed Issue events. */
onRegressed(handler) {
return this.onEvent(handler, 'issue.regressed');
}
/** Handle Crashlytics Velocity Alert events. */
onVelocityAlert(handler) {
return this.onEvent(handler, 'issue.velocityAlert');
}
onEvent(handler, eventType) {
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
eventType,
service: exports.service,
legacyEventType: `providers/firebase.crashlytics/eventTypes/${eventType}`,
triggerResource: this.triggerResource,
opts: this.opts,
});
}
}
exports.IssueBuilder = IssueBuilder;

View File

@@ -0,0 +1,82 @@
import { CloudFunction, EventContext, Change } from '../cloud-functions';
import * as firebase from 'firebase-admin';
/**
* Selects a database instance that will trigger the function.
* If omitted, will pick the default database for your project.
* @param instance The Realtime Database instance to use.
*/
export declare function instance(instance: string): InstanceBuilder;
/**
* Select Firebase Realtime Database Reference to listen to.
*
* This method behaves very similarly to the method of the same name in the
* client and Admin Firebase SDKs. Any change to the Database that affects the
* data at or below the provided `path` will fire an event in Cloud Functions.
*
* There are three important differences between listening to a Realtime
* Database event in Cloud Functions and using the Realtime Database in the
* client and Admin SDKs:
* 1. Cloud Functions allows wildcards in the `path` name. Any `path` component
* in curly brackets (`{}`) is a wildcard that matches all strings. The value
* that matched a certain invocation of a Cloud Function is returned as part
* of the `context.params` object. For example, `ref("messages/{messageId}")`
* matches changes at `/messages/message1` or `/messages/message2`, resulting
* in `context.params.messageId` being set to `"message1"` or `"message2"`,
* respectively.
* 2. Cloud Functions do not fire an event for data that already existed before
* the Cloud Function was deployed.
* 3. Cloud Function events have access to more information, including information
* about the user who triggered the Cloud Function.
* @param ref Path of the database to listen to.
*/
export declare function ref(path: string): RefBuilder;
export declare class InstanceBuilder {
private instance;
private opts;
ref(path: string): RefBuilder;
}
/** Builder used to create Cloud Functions for Firebase Realtime Database References. */
export declare class RefBuilder {
private apps;
private triggerResource;
private opts;
/** Respond to any write that affects a ref. */
onWrite(handler: (change: Change<DataSnapshot>, context: EventContext) => PromiseLike<any> | any): CloudFunction<Change<DataSnapshot>>;
/** Respond to update on a ref. */
onUpdate(handler: (change: Change<DataSnapshot>, context: EventContext) => PromiseLike<any> | any): CloudFunction<Change<DataSnapshot>>;
/** Respond to new data on a ref. */
onCreate(handler: (snapshot: DataSnapshot, context: EventContext) => PromiseLike<any> | any): CloudFunction<DataSnapshot>;
/** Respond to all data being deleted from a ref. */
onDelete(handler: (snapshot: DataSnapshot, context: EventContext) => PromiseLike<any> | any): CloudFunction<DataSnapshot>;
private onOperation<T>(handler, eventType, dataConstructor);
private changeConstructor;
}
export declare class DataSnapshot {
private app;
instance: string;
private _ref;
private _path;
private _data;
private _childPath;
constructor(data: any, path?: string, app?: firebase.app.App, instance?: string);
/** Ref returns a reference to the database with full admin access. */
readonly ref: firebase.database.Reference;
readonly key: string;
val(): any;
exportVal(): any;
getPriority(): string | number | null;
exists(): boolean;
child(childPath: string): DataSnapshot;
forEach(action: (a: DataSnapshot) => boolean): boolean;
hasChild(childPath: string): boolean;
hasChildren(): boolean;
numChildren(): number;
/**
* Prints the value of the snapshot; use '.previous.toJSON()' and '.current.toJSON()' to explicitly see
* the previous and current values of the snapshot.
*/
toJSON(): Object;
private _checkAndConvertToArray(node);
private _dup(childPath?);
private _fullPath();
}

View File

@@ -0,0 +1,315 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const apps_1 = require("../apps");
const cloud_functions_1 = require("../cloud-functions");
const utils_1 = require("../utils");
const config_1 = require("../config");
/** @internal */
exports.provider = 'google.firebase.database';
/** @internal */
exports.service = 'firebaseio.com';
// NOTE(inlined): Should we relax this a bit to allow staging or alternate implementations of our API?
const databaseURLRegex = new RegExp('https://([^.]+).firebaseio.com');
/**
* Selects a database instance that will trigger the function.
* If omitted, will pick the default database for your project.
* @param instance The Realtime Database instance to use.
*/
function instance(instance) {
return _instanceWithOpts(instance, {});
}
exports.instance = instance;
/**
* Select Firebase Realtime Database Reference to listen to.
*
* This method behaves very similarly to the method of the same name in the
* client and Admin Firebase SDKs. Any change to the Database that affects the
* data at or below the provided `path` will fire an event in Cloud Functions.
*
* There are three important differences between listening to a Realtime
* Database event in Cloud Functions and using the Realtime Database in the
* client and Admin SDKs:
* 1. Cloud Functions allows wildcards in the `path` name. Any `path` component
* in curly brackets (`{}`) is a wildcard that matches all strings. The value
* that matched a certain invocation of a Cloud Function is returned as part
* of the `context.params` object. For example, `ref("messages/{messageId}")`
* matches changes at `/messages/message1` or `/messages/message2`, resulting
* in `context.params.messageId` being set to `"message1"` or `"message2"`,
* respectively.
* 2. Cloud Functions do not fire an event for data that already existed before
* the Cloud Function was deployed.
* 3. Cloud Function events have access to more information, including information
* about the user who triggered the Cloud Function.
* @param ref Path of the database to listen to.
*/
function ref(path) {
return _refWithOpts(path, {});
}
exports.ref = ref;
/** @internal */
function _instanceWithOpts(instance, opts) {
return new InstanceBuilder(instance, opts);
}
exports._instanceWithOpts = _instanceWithOpts;
class InstanceBuilder {
/* @internal */
constructor(instance, opts) {
this.instance = instance;
this.opts = opts;
}
ref(path) {
const normalized = utils_1.normalizePath(path);
return new RefBuilder(apps_1.apps(), () => `projects/_/instances/${this.instance}/refs/${normalized}`, this.opts);
}
}
exports.InstanceBuilder = InstanceBuilder;
/** @internal */
function _refWithOpts(path, opts) {
const resourceGetter = () => {
const normalized = utils_1.normalizePath(path);
const databaseURL = config_1.firebaseConfig().databaseURL;
if (!databaseURL) {
throw new Error('Missing expected firebase config value databaseURL, ' +
'config is actually' +
JSON.stringify(config_1.firebaseConfig()) +
'\n If you are unit testing, please set process.env.FIREBASE_CONFIG');
}
const match = databaseURL.match(databaseURLRegex);
if (!match) {
throw new Error('Invalid value for config firebase.databaseURL: ' + databaseURL);
}
const subdomain = match[1];
return `projects/_/instances/${subdomain}/refs/${normalized}`;
};
return new RefBuilder(apps_1.apps(), resourceGetter, opts);
}
exports._refWithOpts = _refWithOpts;
/** Builder used to create Cloud Functions for Firebase Realtime Database References. */
class RefBuilder {
/** @internal */
constructor(apps, triggerResource, opts) {
this.apps = apps;
this.triggerResource = triggerResource;
this.opts = opts;
this.changeConstructor = (raw) => {
let [dbInstance, path] = resourceToInstanceAndPath(raw.context.resource.name);
let before = new DataSnapshot(raw.data.data, path, this.apps.admin, dbInstance);
let after = new DataSnapshot(utils_1.applyChange(raw.data.data, raw.data.delta), path, this.apps.admin, dbInstance);
return {
before: before,
after: after,
};
};
}
/** Respond to any write that affects a ref. */
onWrite(handler) {
return this.onOperation(handler, 'ref.write', this.changeConstructor);
}
/** Respond to update on a ref. */
onUpdate(handler) {
return this.onOperation(handler, 'ref.update', this.changeConstructor);
}
/** Respond to new data on a ref. */
onCreate(handler) {
let dataConstructor = (raw) => {
let [dbInstance, path] = resourceToInstanceAndPath(raw.context.resource.name);
return new DataSnapshot(raw.data.delta, path, this.apps.admin, dbInstance);
};
return this.onOperation(handler, 'ref.create', dataConstructor);
}
/** Respond to all data being deleted from a ref. */
onDelete(handler) {
let dataConstructor = (raw) => {
let [dbInstance, path] = resourceToInstanceAndPath(raw.context.resource.name);
return new DataSnapshot(raw.data.data, path, this.apps.admin, dbInstance);
};
return this.onOperation(handler, 'ref.delete', dataConstructor);
}
onOperation(handler, eventType, dataConstructor) {
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
service: exports.service,
eventType,
legacyEventType: `providers/${exports.provider}/eventTypes/${eventType}`,
triggerResource: this.triggerResource,
dataConstructor: dataConstructor,
before: event => this.apps.retain(),
after: event => this.apps.release(),
opts: this.opts,
});
}
}
exports.RefBuilder = RefBuilder;
/* Utility function to extract database reference from resource string */
/** @internal */
function resourceToInstanceAndPath(resource) {
let resourceRegex = `projects/([^/]+)/instances/([^/]+)/refs(/.+)?`;
let match = resource.match(new RegExp(resourceRegex));
if (!match) {
throw new Error(`Unexpected resource string for Firebase Realtime Database event: ${resource}. ` +
'Expected string in the format of "projects/_/instances/{firebaseioSubdomain}/refs/{ref=**}"');
}
let [, project, dbInstanceName, path] = match;
if (project !== '_') {
throw new Error(`Expect project to be '_' in a Firebase Realtime Database event`);
}
let dbInstance = 'https://' + dbInstanceName + '.firebaseio.com';
return [dbInstance, path];
}
exports.resourceToInstanceAndPath = resourceToInstanceAndPath;
class DataSnapshot {
constructor(data, path, // path will be undefined for the database root
app, instance) {
this.app = app;
if (instance) {
// SDK always supplies instance, but user's unit tests may not
this.instance = instance;
}
else if (app) {
this.instance = app.options.databaseURL;
}
else if (process.env.GCLOUD_PROJECT) {
this.instance =
'https://' + process.env.GCLOUD_PROJECT + '.firebaseio.com';
}
this._path = path;
this._data = data;
}
/** Ref returns a reference to the database with full admin access. */
get ref() {
if (!this.app) {
// may be unpopulated in user's unit tests
throw new Error('Please supply a Firebase app in the constructor for DataSnapshot' +
' in order to use the .ref method.');
}
if (!this._ref) {
this._ref = this.app.database(this.instance).ref(this._fullPath());
}
return this._ref;
}
get key() {
let last = _.last(utils_1.pathParts(this._fullPath()));
return !last || last === '' ? null : last;
}
val() {
let parts = utils_1.pathParts(this._childPath);
let source = this._data;
let node = _.cloneDeep(parts.length ? _.get(source, parts, null) : source);
return this._checkAndConvertToArray(node);
}
// TODO(inlined): figure out what to do here
exportVal() {
return this.val();
}
// TODO(inlined): figure out what to do here
getPriority() {
return 0;
}
exists() {
return !_.isNull(this.val());
}
child(childPath) {
if (!childPath) {
return this;
}
return this._dup(childPath);
}
forEach(action) {
let val = this.val();
if (_.isPlainObject(val)) {
return _.some(val, (value, key) => action(this.child(key)) === true);
}
return false;
}
hasChild(childPath) {
return this.child(childPath).exists();
}
hasChildren() {
let val = this.val();
return _.isPlainObject(val) && _.keys(val).length > 0;
}
numChildren() {
let val = this.val();
return _.isPlainObject(val) ? Object.keys(val).length : 0;
}
/**
* Prints the value of the snapshot; use '.previous.toJSON()' and '.current.toJSON()' to explicitly see
* the previous and current values of the snapshot.
*/
toJSON() {
return this.val();
}
/* Recursive function to check if keys are numeric & convert node object to array if they are */
_checkAndConvertToArray(node) {
if (node === null || typeof node === 'undefined') {
return null;
}
if (typeof node !== 'object') {
return node;
}
let obj = {};
let numKeys = 0;
let maxKey = 0;
let allIntegerKeys = true;
for (let key in node) {
if (!node.hasOwnProperty(key)) {
continue;
}
let childNode = node[key];
obj[key] = this._checkAndConvertToArray(childNode);
numKeys++;
const integerRegExp = /^(0|[1-9]\d*)$/;
if (allIntegerKeys && integerRegExp.test(key)) {
maxKey = Math.max(maxKey, Number(key));
}
else {
allIntegerKeys = false;
}
}
if (allIntegerKeys && maxKey < 2 * numKeys) {
// convert to array.
let array = [];
_.forOwn(obj, (val, key) => {
array[key] = val;
});
return array;
}
return obj;
}
_dup(childPath) {
let dup = new DataSnapshot(this._data, undefined, this.app, this.instance);
[dup._path, dup._childPath] = [this._path, this._childPath];
if (childPath) {
dup._childPath = utils_1.joinPath(dup._childPath, childPath);
}
return dup;
}
_fullPath() {
let out = (this._path || '') + '/' + (this._childPath || '');
return out;
}
}
exports.DataSnapshot = DataSnapshot;

View File

@@ -0,0 +1,36 @@
import * as firebase from 'firebase-admin';
import { CloudFunction, Change, EventContext } from '../cloud-functions';
export declare type DocumentSnapshot = firebase.firestore.DocumentSnapshot;
/**
* Select the Firestore document to listen to for events.
* @param path Full database path to listen to. This includes the name of
* the collection that the document is a part of. For example, if the
* collection is named "users" and the document is named "Ada", then the
* path is "/users/Ada".
*/
export declare function document(path: string): DocumentBuilder;
export declare class DatabaseBuilder {
private database;
private opts;
namespace(namespace: string): NamespaceBuilder;
document(path: string): DocumentBuilder;
}
export declare class NamespaceBuilder {
private database;
private opts;
private namespace;
document(path: string): DocumentBuilder;
}
export declare class DocumentBuilder {
private triggerResource;
private opts;
/** Respond to all document writes (creates, updates, or deletes). */
onWrite(handler: (change: Change<DocumentSnapshot>, context: EventContext) => PromiseLike<any> | any): CloudFunction<Change<DocumentSnapshot>>;
/** Respond only to document updates. */
onUpdate(handler: (change: Change<DocumentSnapshot>, context: EventContext) => PromiseLike<any> | any): CloudFunction<Change<DocumentSnapshot>>;
/** Respond only to document creations. */
onCreate(handler: (snapshot: DocumentSnapshot, context: EventContext) => PromiseLike<any> | any): CloudFunction<DocumentSnapshot>;
/** Respond only to document deletions. */
onDelete(handler: (snapshot: DocumentSnapshot, context: EventContext) => PromiseLike<any> | any): CloudFunction<DocumentSnapshot>;
private onOperation<T>(handler, eventType, dataConstructor);
}

View File

@@ -0,0 +1,182 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("path");
const _ = require("lodash");
const firebase = require("firebase-admin");
const apps_1 = require("../apps");
const cloud_functions_1 = require("../cloud-functions");
const encoder_1 = require("../encoder");
/** @internal */
exports.provider = 'google.firestore';
/** @internal */
exports.service = 'firestore.googleapis.com';
/** @internal */
exports.defaultDatabase = '(default)';
let firestoreInstance;
/**
* Select the Firestore document to listen to for events.
* @param path Full database path to listen to. This includes the name of
* the collection that the document is a part of. For example, if the
* collection is named "users" and the document is named "Ada", then the
* path is "/users/Ada".
*/
function document(path) {
return _documentWithOpts(path, {});
}
exports.document = document;
/** @internal */
// Multiple namespaces are not yet supported by Firestore.
function namespace(namespace) {
return _namespaceWithOpts(namespace, {});
}
exports.namespace = namespace;
/** @internal */
// Multiple databases are not yet supported by Firestore.
function database(database) {
return _databaseWithOpts(database, {});
}
exports.database = database;
/** @internal */
function _databaseWithOpts(database = exports.defaultDatabase, opts) {
return new DatabaseBuilder(database, opts);
}
exports._databaseWithOpts = _databaseWithOpts;
/** @internal */
function _namespaceWithOpts(namespace, opts) {
return _databaseWithOpts(exports.defaultDatabase, opts).namespace(namespace);
}
exports._namespaceWithOpts = _namespaceWithOpts;
/** @internal */
function _documentWithOpts(path, opts) {
return _databaseWithOpts(exports.defaultDatabase, opts).document(path);
}
exports._documentWithOpts = _documentWithOpts;
class DatabaseBuilder {
/** @internal */
constructor(database, opts) {
this.database = database;
this.opts = opts;
}
namespace(namespace) {
return new NamespaceBuilder(this.database, this.opts, namespace);
}
document(path) {
return new NamespaceBuilder(this.database, this.opts).document(path);
}
}
exports.DatabaseBuilder = DatabaseBuilder;
class NamespaceBuilder {
/** @internal */
constructor(database, opts, namespace) {
this.database = database;
this.opts = opts;
this.namespace = namespace;
}
document(path) {
return new DocumentBuilder(() => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error('process.env.GCLOUD_PROJECT is not set.');
}
let database = path_1.posix.join('projects', process.env.GCLOUD_PROJECT, 'databases', this.database);
return path_1.posix.join(database, this.namespace ? `documents@${this.namespace}` : 'documents', path);
}, this.opts);
}
}
exports.NamespaceBuilder = NamespaceBuilder;
function _getValueProto(data, resource, valueFieldName) {
if (_.isEmpty(_.get(data, valueFieldName))) {
// Firestore#snapshot_ takes resource string instead of proto for a non-existent snapshot
return resource;
}
let proto = {
fields: _.get(data, [valueFieldName, 'fields'], {}),
createTime: encoder_1.dateToTimestampProto(_.get(data, [valueFieldName, 'createTime'])),
updateTime: encoder_1.dateToTimestampProto(_.get(data, [valueFieldName, 'updateTime'])),
name: _.get(data, [valueFieldName, 'name'], resource),
};
return proto;
}
/** @internal */
function snapshotConstructor(event) {
if (!firestoreInstance) {
firestoreInstance = firebase.firestore(apps_1.apps().admin);
firestoreInstance.settings({ timestampsInSnapshots: true });
}
let valueProto = _getValueProto(event.data, event.context.resource.name, 'value');
let readTime = encoder_1.dateToTimestampProto(_.get(event, 'data.value.readTime'));
return firestoreInstance.snapshot_(valueProto, readTime, 'json');
}
exports.snapshotConstructor = snapshotConstructor;
/** @internal */
// TODO remove this function when wire format changes to new format
function beforeSnapshotConstructor(event) {
if (!firestoreInstance) {
firestoreInstance = firebase.firestore(apps_1.apps().admin);
firestoreInstance.settings({ timestampsInSnapshots: true });
}
let oldValueProto = _getValueProto(event.data, event.context.resource.name, 'oldValue');
let oldReadTime = encoder_1.dateToTimestampProto(_.get(event, 'data.oldValue.readTime'));
return firestoreInstance.snapshot_(oldValueProto, oldReadTime, 'json');
}
exports.beforeSnapshotConstructor = beforeSnapshotConstructor;
function changeConstructor(raw) {
return cloud_functions_1.Change.fromObjects(beforeSnapshotConstructor(raw), snapshotConstructor(raw));
}
class DocumentBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
// TODO what validation do we want to do here?
}
/** Respond to all document writes (creates, updates, or deletes). */
onWrite(handler) {
return this.onOperation(handler, 'document.write', changeConstructor);
}
/** Respond only to document updates. */
onUpdate(handler) {
return this.onOperation(handler, 'document.update', changeConstructor);
}
/** Respond only to document creations. */
onCreate(handler) {
return this.onOperation(handler, 'document.create', snapshotConstructor);
}
/** Respond only to document deletions. */
onDelete(handler) {
return this.onOperation(handler, 'document.delete', beforeSnapshotConstructor);
}
onOperation(handler, eventType, dataConstructor) {
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
eventType,
service: exports.service,
triggerResource: this.triggerResource,
legacyEventType: `providers/cloud.firestore/eventTypes/${eventType}`,
dataConstructor,
opts: this.opts,
});
}
}
exports.DocumentBuilder = DocumentBuilder;

View File

@@ -0,0 +1,91 @@
/// <reference types="express" />
import * as express from 'express';
import * as firebase from 'firebase-admin';
import { HttpsFunction, Runnable } from '../cloud-functions';
/**
* Handle HTTP requests.
* @param handler A function that takes a request and response object,
* same signature as an Express app.
*/
export declare function onRequest(handler: (req: express.Request, resp: express.Response) => void): HttpsFunction;
/**
* Declares a callable method for clients to call using a Firebase SDK.
* @param handler A method that takes a data and context and returns a value.
*/
export declare function onCall(handler: (data: any, context: CallableContext) => any | Promise<any>): HttpsFunction & Runnable<any>;
/**
* The set of Firebase Functions status codes. The codes are the same at the
* ones exposed by gRPC here:
* https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
*
* Possible values:
* - 'cancelled': The operation was cancelled (typically by the caller).
* - 'unknown': Unknown error or an error from a different error domain.
* - 'invalid-argument': Client specified an invalid argument. Note that this
* differs from 'failed-precondition'. 'invalid-argument' indicates
* arguments that are problematic regardless of the state of the system
* (e.g. an invalid field name).
* - 'deadline-exceeded': Deadline expired before operation could complete.
* For operations that change the state of the system, this error may be
* returned even if the operation has completed successfully. For example,
* a successful response from a server could have been delayed long enough
* for the deadline to expire.
* - 'not-found': Some requested document was not found.
* - 'already-exists': Some document that we attempted to create already
* exists.
* - 'permission-denied': The caller does not have permission to execute the
* specified operation.
* - 'resource-exhausted': Some resource has been exhausted, perhaps a
* per-user quota, or perhaps the entire file system is out of space.
* - 'failed-precondition': Operation was rejected because the system is not
* in a state required for the operation's execution.
* - 'aborted': The operation was aborted, typically due to a concurrency
* issue like transaction aborts, etc.
* - 'out-of-range': Operation was attempted past the valid range.
* - 'unimplemented': Operation is not implemented or not supported/enabled.
* - 'internal': Internal errors. Means some invariants expected by
* underlying system has been broken. If you see one of these errors,
* something is very broken.
* - 'unavailable': The service is currently unavailable. This is most likely
* a transient condition and may be corrected by retrying with a backoff.
* - 'data-loss': Unrecoverable data loss or corruption.
* - 'unauthenticated': The request does not have valid authentication
* credentials for the operation.
*/
export declare type FunctionsErrorCode = 'ok' | 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
/**
* An explicit error that can be thrown from a handler to send an error to the
* client that called the function.
*/
export declare class HttpsError extends Error {
/**
* A standard error code that will be returned to the client. This also
* determines the HTTP status code of the response, as defined in code.proto.
*/
readonly code: FunctionsErrorCode;
/**
* Extra data to be converted to JSON and included in the error response.
*/
readonly details?: any;
constructor(code: FunctionsErrorCode, message?: string, details?: any);
}
/**
* The interface for metadata for the API as passed to the handler.
*/
export interface CallableContext {
/**
* The result of decoding and verifying a Firebase Auth ID token.
*/
auth?: {
uid: string;
token: firebase.auth.DecodedIdToken;
};
/**
* An unverified token for a Firebase Instance ID.
*/
instanceIdToken?: string;
/**
* The raw request handled by the callable.
*/
rawRequest: express.Request;
}

View File

@@ -0,0 +1,359 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const cors = require("cors");
const apps_1 = require("../apps");
const cloud_functions_1 = require("../cloud-functions");
/**
* Handle HTTP requests.
* @param handler A function that takes a request and response object,
* same signature as an Express app.
*/
function onRequest(handler) {
return _onRequestWithOpts(handler, {});
}
exports.onRequest = onRequest;
/**
* Declares a callable method for clients to call using a Firebase SDK.
* @param handler A method that takes a data and context and returns a value.
*/
function onCall(handler) {
return _onCallWithOpts(handler, {});
}
exports.onCall = onCall;
/** @internal */
function _onRequestWithOpts(handler, opts) {
// lets us add __trigger without altering handler:
let cloudFunction = (req, res) => {
handler(req, res);
};
cloudFunction.__trigger = _.assign(cloud_functions_1.optsToTrigger(opts), { httpsTrigger: {} });
// TODO parse the opts
return cloudFunction;
}
exports._onRequestWithOpts = _onRequestWithOpts;
/**
* Standard error codes for different ways a request can fail, as defined by:
* https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
*
* This map is used primarily to convert from a client error code string to
* to the HTTP format error code string, and make sure it's in the supported set.
*/
const errorCodeMap = {
ok: 'OK',
cancelled: 'CANCELLED',
unknown: 'UNKNOWN',
'invalid-argument': 'INVALID_ARGUMENT',
'deadline-exceeded': 'DEADLINE_EXCEEDED',
'not-found': 'NOT_FOUND',
'already-exists': 'ALREADY_EXISTS',
'permission-denied': 'PERMISSION_DENIED',
unauthenticated: 'UNAUTHENTICATED',
'resource-exhausted': 'RESOURCE_EXHAUSTED',
'failed-precondition': 'FAILED_PRECONDITION',
aborted: 'ABORTED',
'out-of-range': 'OUT_OF_RANGE',
unimplemented: 'UNIMPLEMENTED',
internal: 'INTERNAL',
unavailable: 'UNAVAILABLE',
'data-loss': 'DATA_LOSS',
};
/**
* An explicit error that can be thrown from a handler to send an error to the
* client that called the function.
*/
class HttpsError extends Error {
constructor(code, message, details) {
super(message);
// This is a workaround for a bug in TypeScript when extending Error:
// tslint:disable-next-line
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, HttpsError.prototype);
if (!errorCodeMap[code]) {
throw new Error('Unknown error status: ' + code);
}
this.code = code;
this.details = details;
}
/**
* @internal
* A string representation of the Google error code for this error for HTTP.
*/
get status() {
return errorCodeMap[this.code];
}
/**
* @internal
* Returns the canonical http status code for the given error.
*/
get httpStatus() {
switch (this.code) {
case 'ok':
return 200;
case 'cancelled':
return 499;
case 'unknown':
return 500;
case 'invalid-argument':
return 400;
case 'deadline-exceeded':
return 504;
case 'not-found':
return 404;
case 'already-exists':
return 409;
case 'permission-denied':
return 403;
case 'unauthenticated':
return 401;
case 'resource-exhausted':
return 429;
case 'failed-precondition':
return 400;
case 'aborted':
return 409;
case 'out-of-range':
return 400;
case 'unimplemented':
return 501;
case 'internal':
return 500;
case 'unavailable':
return 503;
case 'data-loss':
return 500;
// This should never happen as long as the type system is doing its job.
default:
throw 'Invalid error code: ' + this.code;
}
}
/** @internal */
toJSON() {
const json = {
status: this.status,
message: this.message,
};
if (!_.isUndefined(this.details)) {
json.details = this.details;
}
return json;
}
}
exports.HttpsError = HttpsError;
// Returns true if req is a properly formatted callable request.
function isValidRequest(req) {
// The body must not be empty.
if (!req.body) {
console.warn('Request is missing body.');
return false;
}
// Make sure it's a POST.
if (req.method !== 'POST') {
console.warn('Request has invalid method.', req.method);
return false;
}
// Check that the Content-Type is JSON.
let contentType = (req.header('Content-Type') || '').toLowerCase();
// If it has a charset, just ignore it for now.
const semiColon = contentType.indexOf(';');
if (semiColon >= 0) {
contentType = contentType.substr(0, semiColon).trim();
}
if (contentType !== 'application/json') {
console.warn('Request has incorrect Content-Type.', contentType);
return false;
}
// The body must have data.
if (_.isUndefined(req.body.data)) {
console.warn('Request body is missing data.', req.body);
return false;
}
// TODO(klimt): Allow only whitelisted http headers.
// Verify that the body does not have any extra fields.
const extras = _.omit(req.body, 'data');
if (!_.isEmpty(extras)) {
console.warn('Request body has extra fields.', extras);
return false;
}
return true;
}
const LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
const UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';
/**
* Encodes arbitrary data in our special format for JSON.
* This is exposed only for testing.
*/
/** @internal */
function encode(data) {
if (_.isNull(data) || _.isUndefined(data)) {
return null;
}
// Oddly, _.isFinite(new Number(x)) always returns false, so unwrap Numbers.
if (data instanceof Number) {
data = data.valueOf();
}
if (_.isFinite(data)) {
// Any number in JS is safe to put directly in JSON and parse as a double
// without any loss of precision.
return data;
}
if (_.isBoolean(data)) {
return data;
}
if (_.isString(data)) {
return data;
}
if (_.isArray(data)) {
return _.map(data, encode);
}
if (_.isObject(data)) {
// It's not safe to use _.forEach, because the object might be 'array-like'
// if it has a key called 'length'. Note that this intentionally overrides
// any toJSON method that an object may have.
return _.mapValues(data, encode);
}
// If we got this far, the data is not encodable.
console.error('Data cannot be encoded in JSON.', data);
throw new Error('Data cannot be encoded in JSON: ' + data);
}
exports.encode = encode;
/**
* Decodes our special format for JSON into native types.
* This is exposed only for testing.
*/
/** @internal */
function decode(data) {
if (data === null) {
return data;
}
if (data['@type']) {
switch (data['@type']) {
case LONG_TYPE:
// Fall through and handle this the same as unsigned.
case UNSIGNED_LONG_TYPE: {
// Technically, this could work return a valid number for malformed
// data if there was a number followed by garbage. But it's just not
// worth all the extra code to detect that case.
const value = parseFloat(data.value);
if (_.isNaN(value)) {
console.error('Data cannot be decoded from JSON.', data);
throw new Error('Data cannot be decoded from JSON: ' + data);
}
return value;
}
default: {
console.error('Data cannot be decoded from JSON.', data);
throw new Error('Data cannot be decoded from JSON: ' + data);
}
}
}
if (_.isArray(data)) {
return _.map(data, decode);
}
if (_.isObject(data)) {
// It's not safe to use _.forEach, because the object might be 'array-like'
// if it has a key called 'length'.
return _.mapValues(data, decode);
}
// Anything else is safe to return.
return data;
}
exports.decode = decode;
const corsHandler = cors({ origin: true, methods: 'POST' });
/** @internal */
function _onCallWithOpts(handler, opts) {
const func = (req, res) => __awaiter(this, void 0, void 0, function* () {
try {
if (!isValidRequest(req)) {
console.error('Invalid request', req);
throw new HttpsError('invalid-argument', 'Bad Request');
}
const context = { rawRequest: req };
const authorization = req.header('Authorization');
if (authorization) {
const match = authorization.match(/^Bearer (.*)$/);
if (!match) {
throw new HttpsError('unauthenticated', 'Unauthenticated');
}
const idToken = match[1];
try {
const authToken = yield apps_1.apps()
.admin.auth()
.verifyIdToken(idToken);
context.auth = {
uid: authToken.uid,
token: authToken,
};
}
catch (e) {
throw new HttpsError('unauthenticated', 'Unauthenticated');
}
}
const instanceId = req.header('Firebase-Instance-ID-Token');
if (instanceId) {
// Validating the token requires an http request, so we don't do it.
// If the user wants to use it for something, it will be validated then.
// Currently, the only real use case for this token is for sending
// pushes with FCM. In that case, the FCM APIs will validate the token.
context.instanceIdToken = req.header('Firebase-Instance-ID-Token');
}
const data = decode(req.body.data);
let result = yield handler(data, context);
// Encode the result as JSON to preserve types like Dates.
result = encode(result);
// If there was some result, encode it in the body.
const responseBody = { result };
res.status(200).send(responseBody);
}
catch (error) {
if (!(error instanceof HttpsError)) {
// This doesn't count as an 'explicit' error.
console.error('Unhandled error', error);
error = new HttpsError('internal', 'INTERNAL');
}
const status = error.httpStatus;
const body = { error: error.toJSON() };
res.status(status).send(body);
}
});
// Wrap the function with a cors handler.
const corsFunc = (req, res) => {
return corsHandler(req, res, () => func(req, res));
};
corsFunc.__trigger = _.assign(cloud_functions_1.optsToTrigger(opts), {
httpsTrigger: {},
labels: { 'deployment-callable': 'true' },
});
corsFunc.run = handler;
return corsFunc;
}
exports._onCallWithOpts = _onCallWithOpts;

View File

@@ -0,0 +1,29 @@
import { CloudFunction, EventContext } from '../cloud-functions';
/** Select Cloud Pub/Sub topic to listen to.
* @param topic Name of Pub/Sub topic, must belong to the same project as the function.
*/
export declare function topic(topic: string): TopicBuilder;
/** Builder used to create Cloud Functions for Google Pub/Sub topics. */
export declare class TopicBuilder {
private triggerResource;
private opts;
/** Handle a Pub/Sub message that was published to a Cloud Pub/Sub topic */
onPublish(handler: (message: Message, context: EventContext) => PromiseLike<any> | any): CloudFunction<Message>;
}
/**
* A Pub/Sub message.
*
* This class has an additional .json helper which will correctly deserialize any
* message that was a JSON object when published with the JS SDK. .json will throw
* if the message is not a base64 encoded JSON string.
*/
export declare class Message {
readonly data: string;
readonly attributes: {
[key: string]: string;
};
private _json;
constructor(data: any);
readonly json: any;
toJSON(): any;
}

View File

@@ -0,0 +1,98 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const cloud_functions_1 = require("../cloud-functions");
/** @internal */
exports.provider = 'google.pubsub';
/** @internal */
exports.service = 'pubsub.googleapis.com';
/** Select Cloud Pub/Sub topic to listen to.
* @param topic Name of Pub/Sub topic, must belong to the same project as the function.
*/
function topic(topic) {
return _topicWithOpts(topic, {});
}
exports.topic = topic;
/** @internal */
function _topicWithOpts(topic, opts) {
if (topic.indexOf('/') !== -1) {
throw new Error('Topic name may not have a /');
}
return new TopicBuilder(() => {
if (!process.env.GCLOUD_PROJECT) {
throw new Error('process.env.GCLOUD_PROJECT is not set.');
}
return `projects/${process.env.GCLOUD_PROJECT}/topics/${topic}`;
}, opts);
}
exports._topicWithOpts = _topicWithOpts;
/** Builder used to create Cloud Functions for Google Pub/Sub topics. */
class TopicBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
}
/** Handle a Pub/Sub message that was published to a Cloud Pub/Sub topic */
onPublish(handler) {
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
service: exports.service,
triggerResource: this.triggerResource,
eventType: 'topic.publish',
dataConstructor: raw => new Message(raw.data),
opts: this.opts,
});
}
}
exports.TopicBuilder = TopicBuilder;
/**
* A Pub/Sub message.
*
* This class has an additional .json helper which will correctly deserialize any
* message that was a JSON object when published with the JS SDK. .json will throw
* if the message is not a base64 encoded JSON string.
*/
class Message {
constructor(data) {
[this.data, this.attributes, this._json] = [
data.data,
data.attributes || {},
data.json,
];
}
get json() {
if (typeof this._json === 'undefined') {
this._json = JSON.parse(new Buffer(this.data, 'base64').toString('utf8'));
}
return this._json;
}
toJSON() {
return {
data: this.data,
attributes: this.attributes,
};
}
}
exports.Message = Message;

View File

@@ -0,0 +1,35 @@
import { CloudFunction, EventContext } from '../cloud-functions';
/**
* Handle all updates (including rollbacks) that affect a Remote Config project.
* @param handler A function that takes the updated Remote Config template
* version metadata as an argument.
*/
export declare function onUpdate(handler: (version: TemplateVersion, context: EventContext) => PromiseLike<any> | any): CloudFunction<TemplateVersion>;
/**
* Interface representing a Remote Config template version metadata object that
* was emitted when the project was updated.
*/
export interface TemplateVersion {
/** The version number of the updated Remote Config template. */
versionNumber: number;
/** When the template was updated in format (ISO8601 timestamp). */
updateTime: string;
/** Metadata about the account that performed the update. */
updateUser: RemoteConfigUser;
/** A description associated with the particular Remote Config template. */
description: string;
/** The origin of the caller. */
updateOrigin: string;
/** The type of update action that was performed. */
updateType: string;
/**
* The version number of the Remote Config template that was rolled back to,
* if the update was a rollback.
*/
rollbackSource?: number;
}
export interface RemoteConfigUser {
name?: string;
email: string;
imageUrl?: string;
}

View File

@@ -0,0 +1,52 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2018 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const cloud_functions_1 = require("../cloud-functions");
/** @internal */
exports.provider = 'google.firebase.remoteconfig';
/** @internal */
exports.service = 'firebaseremoteconfig.googleapis.com';
/**
* Handle all updates (including rollbacks) that affect a Remote Config project.
* @param handler A function that takes the updated Remote Config template
* version metadata as an argument.
*/
function onUpdate(handler) {
return _onUpdateWithOpts(handler, {});
}
exports.onUpdate = onUpdate;
/** @internal */
function _onUpdateWithOpts(handler, opts) {
if (!process.env.GCLOUD_PROJECT) {
throw new Error('process.env.GCLOUD_PROJECT is not set.');
}
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
service: exports.service,
triggerResource: () => `projects/${process.env.GCLOUD_PROJECT}`,
eventType: 'update',
opts: opts,
});
}
exports._onUpdateWithOpts = _onUpdateWithOpts;

View File

@@ -0,0 +1,85 @@
import { CloudFunction, EventContext } from '../cloud-functions';
/**
* The optional bucket function allows you to choose which buckets' events to handle.
* This step can be bypassed by calling object() directly, which will use the default
* Cloud Storage for Firebase bucket.
* @param bucket Name of the Google Cloud Storage bucket to listen to.
*/
export declare function bucket(bucket?: string): BucketBuilder;
/**
* Handle events related to Cloud Storage objects.
*/
export declare function object(): ObjectBuilder;
export declare class BucketBuilder {
private triggerResource;
private opts;
/** Handle events for objects in this bucket. */
object(): ObjectBuilder;
}
export declare class ObjectBuilder {
private triggerResource;
private opts;
/** Respond to archiving of an object, this is only for buckets that enabled object versioning. */
onArchive(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
/** Respond to the deletion of an object (not to archiving, if object versioning is enabled). */
onDelete(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
/** Respond to the successful creation of an object. */
onFinalize(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
/** Respond to metadata updates of existing objects. */
onMetadataUpdate(handler: (object: ObjectMetadata, context: EventContext) => PromiseLike<any> | any): CloudFunction<ObjectMetadata>;
private onOperation(handler, eventType);
}
export interface ObjectMetadata {
kind: string;
id: string;
bucket: string;
storageClass: string;
size: string;
timeCreated: string;
updated: string;
selfLink?: string;
name?: string;
generation?: string;
contentType?: string;
metageneration?: string;
timeDeleted?: string;
timeStorageClassUpdated?: string;
md5Hash?: string;
mediaLink?: string;
contentEncoding?: string;
contentDisposition?: string;
contentLanguage?: string;
cacheControl?: string;
metadata?: {
[key: string]: string;
};
acl?: [{
kind?: string;
id?: string;
selfLink?: string;
bucket?: string;
object?: string;
generation?: string;
entity?: string;
role?: string;
email?: string;
entityId?: string;
domain?: string;
projectTeam?: {
projectNumber?: string;
team?: string;
};
etag?: string;
}];
owner?: {
entity?: string;
entityId?: string;
};
crc32c?: string;
componentCount?: string;
etag?: string;
customerEncryption?: {
encryptionAlgorithm?: string;
keySha256?: string;
};
}

View File

@@ -0,0 +1,118 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const cloud_functions_1 = require("../cloud-functions");
const config_1 = require("../config");
/** @internal */
exports.provider = 'google.storage';
/** @internal */
exports.service = 'storage.googleapis.com';
/**
* The optional bucket function allows you to choose which buckets' events to handle.
* This step can be bypassed by calling object() directly, which will use the default
* Cloud Storage for Firebase bucket.
* @param bucket Name of the Google Cloud Storage bucket to listen to.
*/
function bucket(bucket) {
return _bucketWithOpts({}, bucket);
}
exports.bucket = bucket;
/**
* Handle events related to Cloud Storage objects.
*/
function object() {
return _objectWithOpts({});
}
exports.object = object;
/** @internal */
function _bucketWithOpts(opts, bucket) {
const resourceGetter = () => {
bucket = bucket || config_1.firebaseConfig().storageBucket;
if (!bucket) {
throw new Error('Missing bucket name. If you are unit testing, please provide a bucket name' +
' through `functions.storage.bucket(bucketName)`, or set process.env.FIREBASE_CONFIG.');
}
if (!/^[a-z\d][a-z\d\\._-]{1,230}[a-z\d]$/.test(bucket)) {
throw new Error(`Invalid bucket name ${bucket}`);
}
return `projects/_/buckets/${bucket}`;
};
return new BucketBuilder(resourceGetter, opts);
}
exports._bucketWithOpts = _bucketWithOpts;
/** @internal */
function _objectWithOpts(opts) {
return _bucketWithOpts(opts).object();
}
exports._objectWithOpts = _objectWithOpts;
class BucketBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
}
/** Handle events for objects in this bucket. */
object() {
return new ObjectBuilder(this.triggerResource, this.opts);
}
}
exports.BucketBuilder = BucketBuilder;
class ObjectBuilder {
/** @internal */
constructor(triggerResource, opts) {
this.triggerResource = triggerResource;
this.opts = opts;
}
/** @internal */
onChange(handler) {
throw new Error('"onChange" is now deprecated, please use "onArchive", "onDelete", ' +
'"onFinalize", or "onMetadataUpdate".');
}
/** Respond to archiving of an object, this is only for buckets that enabled object versioning. */
onArchive(handler) {
return this.onOperation(handler, 'object.archive');
}
/** Respond to the deletion of an object (not to archiving, if object versioning is enabled). */
onDelete(handler) {
return this.onOperation(handler, 'object.delete');
}
/** Respond to the successful creation of an object. */
onFinalize(handler) {
return this.onOperation(handler, 'object.finalize');
}
/** Respond to metadata updates of existing objects. */
onMetadataUpdate(handler) {
return this.onOperation(handler, 'object.metadataUpdate');
}
onOperation(handler, eventType) {
return cloud_functions_1.makeCloudFunction({
handler,
provider: exports.provider,
service: exports.service,
eventType,
triggerResource: this.triggerResource,
opts: this.opts,
});
}
}
exports.ObjectBuilder = ObjectBuilder;

View File

@@ -0,0 +1,6 @@
export declare function normalizePath(path: string): string;
export declare function pathParts(path: string): string[];
export declare function joinPath(base: string, child: string): string;
export declare function applyChange(src: any, dest: any): any;
export declare function pruneNulls(obj: any): any;
export declare function valAt(source: any, path?: string): any;

View File

@@ -0,0 +1,97 @@
"use strict";
// The MIT License (MIT)
//
// Copyright (c) 2017 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
function normalizePath(path) {
if (!path) {
return '';
}
return path.replace(/^\//, '').replace(/\/$/, '');
}
exports.normalizePath = normalizePath;
function pathParts(path) {
if (!path || path === '' || path === '/') {
return [];
}
return normalizePath(path).split('/');
}
exports.pathParts = pathParts;
function joinPath(base, child) {
return pathParts(base)
.concat(pathParts(child))
.join('/');
}
exports.joinPath = joinPath;
function applyChange(src, dest) {
// if not mergeable, don't merge
if (!_.isPlainObject(dest) || !_.isPlainObject(src)) {
return dest;
}
return pruneNulls(_.merge({}, src, dest));
}
exports.applyChange = applyChange;
function pruneNulls(obj) {
for (let key in obj) {
if (obj[key] === null) {
delete obj[key];
}
else if (_.isPlainObject(obj[key])) {
pruneNulls(obj[key]);
}
}
return obj;
}
exports.pruneNulls = pruneNulls;
function valAt(source, path) {
if (source === null) {
return null;
}
else if (typeof source !== 'object') {
return path ? null : source;
}
let parts = pathParts(path);
if (!parts.length) {
return source;
}
let cur = source;
let leaf;
while (parts.length) {
let key = parts.shift();
if (cur[key] === null || leaf) {
return null;
}
else if (typeof cur[key] === 'object') {
if (parts.length) {
cur = cur[key];
}
else {
return cur[key];
}
}
else {
leaf = cur[key];
}
}
return leaf;
}
exports.valAt = valAt;

View File

@@ -0,0 +1,447 @@
# Change Log
All notable changes to this project will be documented in this file starting from version **v4.0.0**.
This project adheres to [Semantic Versioning](http://semver.org/).
## 8.4.0 - 2018-11-14
### New Functionality
- Add verify option for nonce validation (#540) ([e7938f06fdf2ed3aa88745b72b8ae4ee66c2d0d0](https://github.com/auth0/node-jsonwebtoken/commit/e7938f06fdf2ed3aa88745b72b8ae4ee66c2d0d0)), closes [#540](https://github.com/auth0/node-jsonwebtoken/issues/540)
### Bug Fixes
- Updating Node version in Engines spec in package.json (#528) ([cfd1079305170a897dee6a5f55039783e6ee2711](https://github.com/auth0/node-jsonwebtoken/commit/cfd1079305170a897dee6a5f55039783e6ee2711)), closes [#528](https://github.com/auth0/node-jsonwebtoken/issues/528) [#509](https://github.com/auth0/node-jsonwebtoken/issues/509)
- Fixed error message when empty string passed as expiresIn or notBefore option (#531) ([7f9604ac98d4d0ff8d873c3d2b2ea64bd285cb76](https://github.com/auth0/node-jsonwebtoken/commit/7f9604ac98d4d0ff8d873c3d2b2ea64bd285cb76)), closes [#531](https://github.com/auth0/node-jsonwebtoken/issues/531)
### Docs
- Update README.md (#527) ([b76f2a80f5229ee5cde321dd2ff14aa5df16d283](https://github.com/auth0/node-jsonwebtoken/commit/b76f2a80f5229ee5cde321dd2ff14aa5df16d283)), closes [#527](https://github.com/auth0/node-jsonwebtoken/issues/527)
- Update README.md (#538) ([1956c4006472fd285b8a85074257cbdbe9131cbf](https://github.com/auth0/node-jsonwebtoken/commit/1956c4006472fd285b8a85074257cbdbe9131cbf)), closes [#538](https://github.com/auth0/node-jsonwebtoken/issues/538)
- Edited the README.md to make certain parts of the document for the api easier to read, emphasizing the examples. (#548) ([dc89a641293d42f72ecfc623ce2eabc33954cb9d](https://github.com/auth0/node-jsonwebtoken/commit/dc89a641293d42f72ecfc623ce2eabc33954cb9d)), closes [#548](https://github.com/auth0/node-jsonwebtoken/issues/548)
- Document NotBeforeError (#529) ([29cd654b956529e939ae8f8c30b9da7063aad501](https://github.com/auth0/node-jsonwebtoken/commit/29cd654b956529e939ae8f8c30b9da7063aad501)), closes [#529](https://github.com/auth0/node-jsonwebtoken/issues/529)
### Test Improvements
- Use lolex for faking date in tests (#491) ([677ead6d64482f2067b11437dda07309abe73cfa](https://github.com/auth0/node-jsonwebtoken/commit/677ead6d64482f2067b11437dda07309abe73cfa)), closes [#491](https://github.com/auth0/node-jsonwebtoken/issues/491)
- Update dependencies used for running tests (#518) ([5498bdc4865ffb2ba2fd44d889fad7e83873bb33](https://github.com/auth0/node-jsonwebtoken/commit/5498bdc4865ffb2ba2fd44d889fad7e83873bb33)), closes [#518](https://github.com/auth0/node-jsonwebtoken/issues/518)
- Minor test refactoring for recently added tests (#504) ([e2860a9d2a412627d79741a95bc7159971b923b9](https://github.com/auth0/node-jsonwebtoken/commit/e2860a9d2a412627d79741a95bc7159971b923b9)), closes [#504](https://github.com/auth0/node-jsonwebtoken/issues/504)
- Create and implement async/sync test helpers (#523) ([683d8a9b31ad6327948f84268bd2c8e4350779d1](https://github.com/auth0/node-jsonwebtoken/commit/683d8a9b31ad6327948f84268bd2c8e4350779d1)), closes [#523](https://github.com/auth0/node-jsonwebtoken/issues/523)
- Refactor tests related to audience and aud (#503) ([53d405e0223cce7c83cb51ecf290ca6bec1e9679](https://github.com/auth0/node-jsonwebtoken/commit/53d405e0223cce7c83cb51ecf290ca6bec1e9679)), closes [#503](https://github.com/auth0/node-jsonwebtoken/issues/503)
- Refactor tests related to expiresIn and exp (#501) ([72f0d9e5b11a99082250665d1200c58182903fa6](https://github.com/auth0/node-jsonwebtoken/commit/72f0d9e5b11a99082250665d1200c58182903fa6)), closes [#501](https://github.com/auth0/node-jsonwebtoken/issues/501)
- Refactor tests related to iat and maxAge (#507) ([877bd57ab2aca9b7d230805b21f921baed3da169](https://github.com/auth0/node-jsonwebtoken/commit/877bd57ab2aca9b7d230805b21f921baed3da169)), closes [#507](https://github.com/auth0/node-jsonwebtoken/issues/507)
- Refactor tests related to iss and issuer (#543) ([0906a3fa80f52f959ac1b6343d3024ce5c7e9dea](https://github.com/auth0/node-jsonwebtoken/commit/0906a3fa80f52f959ac1b6343d3024ce5c7e9dea)), closes [#543](https://github.com/auth0/node-jsonwebtoken/issues/543)
- Refactor tests related to kid and keyid (#545) ([88645427a0adb420bd3e149199a2a6bf1e17277e](https://github.com/auth0/node-jsonwebtoken/commit/88645427a0adb420bd3e149199a2a6bf1e17277e)), closes [#545](https://github.com/auth0/node-jsonwebtoken/issues/545)
- Refactor tests related to notBefore and nbf (#497) ([39adf87a6faef3df984140f88e6724ddd709fd89](https://github.com/auth0/node-jsonwebtoken/commit/39adf87a6faef3df984140f88e6724ddd709fd89)), closes [#497](https://github.com/auth0/node-jsonwebtoken/issues/497)
- Refactor tests related to subject and sub (#505) ([5a7fa23c0b4ac6c25304dab8767ef840b43a0eca](https://github.com/auth0/node-jsonwebtoken/commit/5a7fa23c0b4ac6c25304dab8767ef840b43a0eca)), closes [#505](https://github.com/auth0/node-jsonwebtoken/issues/505)
- Implement async/sync tests for exp claim (#536) ([9ae3f207ac64b7450ea0a3434418f5ca58d8125e](https://github.com/auth0/node-jsonwebtoken/commit/9ae3f207ac64b7450ea0a3434418f5ca58d8125e)), closes [#536](https://github.com/auth0/node-jsonwebtoken/issues/536)
- Implement async/sync tests for nbf claim (#537) ([88bc965061ed65299a395f42a100fb8f8c3c683e](https://github.com/auth0/node-jsonwebtoken/commit/88bc965061ed65299a395f42a100fb8f8c3c683e)), closes [#537](https://github.com/auth0/node-jsonwebtoken/issues/537)
- Implement async/sync tests for sub claim (#534) ([342b07bb105a35739eb91265ba5b9dd33c300fc6](https://github.com/auth0/node-jsonwebtoken/commit/342b07bb105a35739eb91265ba5b9dd33c300fc6)), closes [#534](https://github.com/auth0/node-jsonwebtoken/issues/534)
- Implement async/sync tests for the aud claim (#535) ([1c8ff5a68e6da73af2809c9d87faaf78602c99bb](https://github.com/auth0/node-jsonwebtoken/commit/1c8ff5a68e6da73af2809c9d87faaf78602c99bb)), closes [#535](https://github.com/auth0/node-jsonwebtoken/issues/535)
### CI
- Added Istanbul to check test-coverage (#468) ([9676a8306428a045e34c3987bd0680fb952b44e3](https://github.com/auth0/node-jsonwebtoken/commit/9676a8306428a045e34c3987bd0680fb952b44e3)), closes [#468](https://github.com/auth0/node-jsonwebtoken/issues/468)
- Complete ESLint conversion and cleanup (#490) ([cb1d2e1e40547f7ecf29fa6635041df6cbba7f40](https://github.com/auth0/node-jsonwebtoken/commit/cb1d2e1e40547f7ecf29fa6635041df6cbba7f40)), closes [#490](https://github.com/auth0/node-jsonwebtoken/issues/490)
- Make code-coverage mandatory when running tests (#495) ([fb0084a78535bfea8d0087c0870e7e3614a2cbe5](https://github.com/auth0/node-jsonwebtoken/commit/fb0084a78535bfea8d0087c0870e7e3614a2cbe5)), closes [#495](https://github.com/auth0/node-jsonwebtoken/issues/495)
## 8.3.0 - 2018-06-11
- docs: add some clarifications (#473) ([cd33cc81f06068b9df6c224d300dc6f70d8904ab](https://github.com/auth0/node-jsonwebtoken/commit/cd33cc81f06068b9df6c224d300dc6f70d8904ab)), closes [#473](https://github.com/auth0/node-jsonwebtoken/issues/473)
- ci: fix ci execution, remove not needed script (#472) ([c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5](https://github.com/auth0/node-jsonwebtoken/commit/c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5)), closes [#472](https://github.com/auth0/node-jsonwebtoken/issues/472)
- new feature: Secret callback revisited (#480) ([d01cc7bcbdeb606d997a580f967b3169fcc622ba](https://github.com/auth0/node-jsonwebtoken/commit/d01cc7bcbdeb606d997a580f967b3169fcc622ba)), closes [#480](https://github.com/auth0/node-jsonwebtoken/issues/480)
- docs:Update README.md (#461) ([f0e0954505f274da95a8d9603598e455b4d2c894](https://github.com/auth0/node-jsonwebtoken/commit/f0e0954505f274da95a8d9603598e455b4d2c894)), closes [#461](https://github.com/auth0/node-jsonwebtoken/issues/461)
## 8.2.2 - 2018-05-30
- security: deps: jws@3.1.5 (#477) ([ebde9b7cc75cb7ab5176de7ebc4a1d6a8f05bd51](https://github.com/auth0/node-jsonwebtoken/commit/ebde9b7cc75cb7ab5176de7ebc4a1d6a8f05bd51)), closes [#465](https://github.com/auth0/node-jsonwebtoken/issues/465)
- docs: add some clarifications (#473) ([cd33cc81f06068b9df6c224d300dc6f70d8904ab](https://github.com/auth0/node-jsonwebtoken/commit/cd33cc81f06068b9df6c224d300dc6f70d8904ab)), closes [#473](https://github.com/auth0/node-jsonwebtoken/issues/473)
- ci: fix ci execution, remove not needed script (#472) ([c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5](https://github.com/auth0/node-jsonwebtoken/commit/c8ff7b2c3ffcd954a64a0273c20a7d1b22339aa5)), closes [#472](https://github.com/auth0/node-jsonwebtoken/issues/472)
- docs: Update README.md (#461) ([f0e0954505f274da95a8d9603598e455b4d2c894](https://github.com/auth0/node-jsonwebtoken/commit/f0e0954505f274da95a8d9603598e455b4d2c894)), closes [#461](https://github.com/auth0/node-jsonwebtoken/issues/461)
## 8.2.1 - 2018-04-05
- bug fix: Check payload is not null when decoded. (#444) ([1232ae9352ce5fd1ca6c593291ce6ad0834a1ff5](https://github.com/auth0/node-jsonwebtoken/commit/1232ae9352ce5fd1ca6c593291ce6ad0834a1ff5))
- docs: Clarify that buffer/string payloads must be JSON (#442) ([e8ac1be7565a3fd986d40cb5e31a9f6c4d9aed1b](https://github.com/auth0/node-jsonwebtoken/commit/e8ac1be7565a3fd986d40cb5e31a9f6c4d9aed1b))
## 8.2.0 - 2018-03-02
- Add a new mutatePayload option (#446) ([d6d7c5e5103f05a92d3633ac190d3025a0455be0](https://github.com/auth0/node-jsonwebtoken/commit/d6d7c5e5103f05a92d3633ac190d3025a0455be0))
## 8.1.1 - 2018-01-22
- ci: add newer node versions to build matrix (#428) ([83f3eee44e122da06f812d7da4ace1fa26c24d9d](https://github.com/auth0/node-jsonwebtoken/commit/83f3eee44e122da06f812d7da4ace1fa26c24d9d))
- deps: Bump ms version to add support for negative numbers (#438) ([25e0e624545eaef76f3c324a134bf103bc394724](https://github.com/auth0/node-jsonwebtoken/commit/25e0e624545eaef76f3c324a134bf103bc394724))
- docs: Minor typo (#424) ([dddcb73ac05de11b81feeb629f6cf78dd03d2047](https://github.com/auth0/node-jsonwebtoken/commit/dddcb73ac05de11b81feeb629f6cf78dd03d2047))
- bug fix: Not Before (nbf) calculated based on iat/timestamp (#437) ([2764a64908d97c043d62eba0bf6c600674f9a6d6](https://github.com/auth0/node-jsonwebtoken/commit/2764a64908d97c043d62eba0bf6c600674f9a6d6)), closes [#435](https://github.com/auth0/node-jsonwebtoken/issues/435)
## 8.1.0 - 2017-10-09
- #402: Don't fail if captureStackTrace is not a function (#410) ([77ee965d9081faaf21650f266399f203f69533c5](https://github.com/auth0/node-jsonwebtoken/commit/77ee965d9081faaf21650f266399f203f69533c5))
- #403: Clarify error wording for "Expected object" error. (#409) ([bb27eb346f0ff675a320b2de16b391a7cfeadc58](https://github.com/auth0/node-jsonwebtoken/commit/bb27eb346f0ff675a320b2de16b391a7cfeadc58))
- Enhance audience check to verify against regular expressions (#398) ([81501a17da230af7b74a3f7535ab5cd3a19c8315](https://github.com/auth0/node-jsonwebtoken/commit/81501a17da230af7b74a3f7535ab5cd3a19c8315))
## 8.0.1 - 2017-09-12
- Remove `lodash.isarray` dependency (#394) ([7508e8957cb1c778f72fa9a363a7b135b3c9c36d](https://github.com/auth0/node-jsonwebtoken/commit/7508e8957cb1c778f72fa9a363a7b135b3c9c36d))
## 8.0.0 - 2017-09-06
**Breaking changes: See [Migration notes from v7](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8)**
- docs: readme, migration notes ([12cd8f7f47224f904f6b8f39d1dee73775de4f6f](https://github.com/auth0/node-jsonwebtoken/commit/12cd8f7f47224f904f6b8f39d1dee73775de4f6f))
- verify: remove process.nextTick (#302) ([3305cf04e3f674b9fb7e27c9b14ddd159650ff82](https://github.com/auth0/node-jsonwebtoken/commit/3305cf04e3f674b9fb7e27c9b14ddd159650ff82))
- Reduce size of NPM package (#347) ([0be5409ac6592eeaae373dce91ec992fa101bd8a](https://github.com/auth0/node-jsonwebtoken/commit/0be5409ac6592eeaae373dce91ec992fa101bd8a))
- Remove joi to shrink module size (#348) ([2e7e68dbd59e845cdd940afae0a296f48438445f](https://github.com/auth0/node-jsonwebtoken/commit/2e7e68dbd59e845cdd940afae0a296f48438445f))
- maxAge: Add validation to timespan result ([66a4f8b996c8357727ce62a84605a005b2f5eb18](https://github.com/auth0/node-jsonwebtoken/commit/66a4f8b996c8357727ce62a84605a005b2f5eb18))
## 7.4.3 - 2017-08-17
- Fix breaking change on 7.4.2 for empty secret + "none" algorithm (sync code style) ([PR 386](https://github.com/auth0/node-jsonwebtoken/pull/386))
## 7.4.2 - 2017-08-04
- bugfix: sign: add check to be sure secret has a value ([c584d1cbc34b788977b36f17cd57ab2212f1230e](https://github.com/auth0/node-jsonwebtoken/commit/c584d1cbc34b788977b36f17cd57ab2212f1230e))
- docs: about refreshing tokens ([016fc10b847bfbb76b82171cb530f32d7da2001b](https://github.com/auth0/node-jsonwebtoken/commit/016fc10b847bfbb76b82171cb530f32d7da2001b))
- docs: verifying with base64 encoded secrets ([c25e9906801f89605080cc71b3ee23a5e45a5811](https://github.com/auth0/node-jsonwebtoken/commit/c25e9906801f89605080cc71b3ee23a5e45a5811))
- tests: Add tests for ES256 ([89900ea00735f76b04f437c9f542285b420fa9cb](https://github.com/auth0/node-jsonwebtoken/commit/89900ea00735f76b04f437c9f542285b420fa9cb))
- docs: document keyid as option (#361) ([00086c2c006d7fc1a47bae02fa87d194d79aa558](https://github.com/auth0/node-jsonwebtoken/commit/00086c2c006d7fc1a47bae02fa87d194d79aa558))
- docs: readme: Using private key with passpharase (#353) ([27a7f1d4f35b662426ff0270526d48658da4c8b7](https://github.com/auth0/node-jsonwebtoken/commit/27a7f1d4f35b662426ff0270526d48658da4c8b7))
## 7.4.1 - 2017-05-17
- bump ms to v2 due a ReDoS vulnerability (#352) ([adcfd6ae4088c838769d169f8cd9154265aa13e0](https://github.com/auth0/node-jsonwebtoken/commit/adcfd6ae4088c838769d169f8cd9154265aa13e0))
## 7.4.0 - 2017-04-24
- Add docs about numeric date fields ([659f73119900a4d837650d9b3f5af4e64a2f843b](https://github.com/auth0/node-jsonwebtoken/commit/659f73119900a4d837650d9b3f5af4e64a2f843b))
- Make Options object optional for callback-ish sign ([e202c4fd00c35a24e9ab606eab89186ade13d0cc](https://github.com/auth0/node-jsonwebtoken/commit/e202c4fd00c35a24e9ab606eab89186ade13d0cc))
## 7.3.0 - 2017-02-13
- Add more information to `maxAge` option in README ([1b0592e99cc8def293eed177e2575fa7f1cf7aa5](https://github.com/auth0/node-jsonwebtoken/commit/1b0592e99cc8def293eed177e2575fa7f1cf7aa5))
- Add `clockTimestamp` option to `verify()` you can set the current time in seconds with it (#274) ([8fdc1504f4325e7003894ffea078da9cba5208d9](https://github.com/auth0/node-jsonwebtoken/commit/8fdc1504f4325e7003894ffea078da9cba5208d9))
- Fix handling non string tokens on `verify()` input (#305) ([1b6ec8d466504f58c5a6e2dae3360c828bad92fb](https://github.com/auth0/node-jsonwebtoken/commit/1b6ec8d466504f58c5a6e2dae3360c828bad92fb)), closes [#305](https://github.com/auth0/node-jsonwebtoken/issues/305)
- Fixed a simple typo in docs (#287) ([a54240384e24e18c00e75884295306db311d0cb7](https://github.com/auth0/node-jsonwebtoken/commit/a54240384e24e18c00e75884295306db311d0cb7)), closes [#287](https://github.com/auth0/node-jsonwebtoken/issues/287)
- Raise jws.decode error to avoid confusion with "invalid token" error (#294) ([7f68fe06c88d5c5653785bd66bc68c5b20e1bd8e](https://github.com/auth0/node-jsonwebtoken/commit/7f68fe06c88d5c5653785bd66bc68c5b20e1bd8e))
- rauchg/ms.js changed to zeit/ms (#303) ([35d84152a6b716d757cb5b1dd3c79fe3a1bc0628](https://github.com/auth0/node-jsonwebtoken/commit/35d84152a6b716d757cb5b1dd3c79fe3a1bc0628))
## 7.2.1 - 2016-12-07
- add nsp check to find vulnerabilities on npm test ([4219c34b5346811c07f520f10516cc495bcc70dd](https://github.com/auth0/node-jsonwebtoken/commit/4219c34b5346811c07f520f10516cc495bcc70dd))
- revert to joi@^6 to keep ES5 compatibility ([51d4796c07344bf817687f7ccfeef78f00bf5b4f](https://github.com/auth0/node-jsonwebtoken/commit/51d4796c07344bf817687f7ccfeef78f00bf5b4f))
## 7.2.0 - 2016-12-06
- improve the documentation for expiration ([771e0b5f9bed90771fb79140eb38e51a3ecac8f0](https://github.com/auth0/node-jsonwebtoken/commit/771e0b5f9bed90771fb79140eb38e51a3ecac8f0))
- Restructured a sentence ([ccc7610187a862f7a50177eadc9152eef26cd065](https://github.com/auth0/node-jsonwebtoken/commit/ccc7610187a862f7a50177eadc9152eef26cd065))
- Allow `keyid` on `sign`. ([b412be91b89acb3a742bb609d3b54e47e1dfc441](https://github.com/auth0/node-jsonwebtoken/commit/b412be91b89acb3a742bb609d3b54e47e1dfc441))
- upgrade joi ([715e3d928023d414d45c6dc3f096a7c8448139ae](https://github.com/auth0/node-jsonwebtoken/commit/715e3d928023d414d45c6dc3f096a7c8448139ae))
- upgrade to latest nodes and Travis infrastructure ([3febcc1dd23ecdec1abbf89313959941d15eb47a](https://github.com/auth0/node-jsonwebtoken/commit/3febcc1dd23ecdec1abbf89313959941d15eb47a))
## 7.1.10 - 2016-12-06
- Bump node-jws version number ([07813dd7194630c9f452684279178af76464a759](https://github.com/auth0/node-jsonwebtoken/commit/07813dd7194630c9f452684279178af76464a759))
- improve the documentation for expiration ([771e0b5f9bed90771fb79140eb38e51a3ecac8f0](https://github.com/auth0/node-jsonwebtoken/commit/771e0b5f9bed90771fb79140eb38e51a3ecac8f0))
## 7.1.9 - 2016-08-11
- Revert "Merge branch 'venatir-master'" ([d06359ef3b4e619680e043ee7c16adda16598f52](https://github.com/auth0/node-jsonwebtoken/commit/d06359ef3b4e619680e043ee7c16adda16598f52))
## 7.1.8 - 2016-08-10
- Fixed tests, however typ: 'JWT' should not be in the options at all, so please review other tests ([01903bcdc61b4ed429acbbd1fe0ffe0db364473b](https://github.com/auth0/node-jsonwebtoken/commit/01903bcdc61b4ed429acbbd1fe0ffe0db364473b))
- Removing unnecessary extra decoding. jwtString is already verified as valid and signature checked ([55d5834f7b637011e1d8b927ff78a92a5fd521cf](https://github.com/auth0/node-jsonwebtoken/commit/55d5834f7b637011e1d8b927ff78a92a5fd521cf))
- update changelog ([5117aacd0118a10331889a64e61d8186112d8a23](https://github.com/auth0/node-jsonwebtoken/commit/5117aacd0118a10331889a64e61d8186112d8a23))
## 7.1.7 - 2016-07-29
- Use lodash.once instead of unlicensed/unmaintained cb ([3ac95ad93ef3068a64e03d8d14deff231b1ed529](https://github.com/auth0/node-jsonwebtoken/commit/3ac95ad93ef3068a64e03d8d14deff231b1ed529))
## 7.1.6 - 2016-07-15
- fix issue with buffer payload. closes #216 ([6b50ff324b4dfd2cb0e49b666f14a6672d015b22](https://github.com/auth0/node-jsonwebtoken/commit/6b50ff324b4dfd2cb0e49b666f14a6672d015b22)), closes [#216](https://github.com/auth0/node-jsonwebtoken/issues/216)
## 7.1.5 - 2016-07-15
- update jws in package.json ([b6260951eefc68aae5f4ede359210761f901ff7a](https://github.com/auth0/node-jsonwebtoken/commit/b6260951eefc68aae5f4ede359210761f901ff7a))
## 7.1.4 - 2016-07-14
- add redundant test ([bece8816096f324511c3efcb8db0e64b75d757a1](https://github.com/auth0/node-jsonwebtoken/commit/bece8816096f324511c3efcb8db0e64b75d757a1))
- fix an issue of double callback on error ([758ca5eeca2f1b06c32c9fce70642bf488b2e52b](https://github.com/auth0/node-jsonwebtoken/commit/758ca5eeca2f1b06c32c9fce70642bf488b2e52b))
## 7.1.2 - 2016-07-12
- do not stringify the payload when signing async - closes #224 ([084f537d3dfbcef2bea411cc0a1515899cc8aa21](https://github.com/auth0/node-jsonwebtoken/commit/084f537d3dfbcef2bea411cc0a1515899cc8aa21)), closes [#224](https://github.com/auth0/node-jsonwebtoken/issues/224)
## 7.1.1 - 2016-07-12
- do not mutate options in jwt.verify, closes #227 ([63263a28a268624dab0927b9ad86fffa44a10f84](https://github.com/auth0/node-jsonwebtoken/commit/63263a28a268624dab0927b9ad86fffa44a10f84)), closes [#227](https://github.com/auth0/node-jsonwebtoken/issues/227)
- refactor into multiple files ([e11d505207fa33501298300c9accbfb809d8748d](https://github.com/auth0/node-jsonwebtoken/commit/e11d505207fa33501298300c9accbfb809d8748d))
## 7.1.0 - 2016-07-12
- Exp calculated based on iat. fix #217 ([757a16e0e35ad19f9e456820f55d5d9f3fc76aee](https://github.com/auth0/node-jsonwebtoken/commit/757a16e0e35ad19f9e456820f55d5d9f3fc76aee)), closes [#217](https://github.com/auth0/node-jsonwebtoken/issues/217)
## 7.0.0 - 2016-05-19
- change jwt.sign to return errors on callback instead of throwing errors ([1e46c5a42aa3dab8478efa4081d8f8f5c5485d56](https://github.com/auth0/node-jsonwebtoken/commit/1e46c5a42aa3dab8478efa4081d8f8f5c5485d56))
## 6.2.0 - 2016-04-29
- add support for `options.clockTolerance` to `jwt.verify` ([65ddea934f226bf06bc9d6a55be9587515cfc38d](https://github.com/auth0/node-jsonwebtoken/commit/65ddea934f226bf06bc9d6a55be9587515cfc38d))
## 6.1.2 - 2016-04-29
- fix sign method for node.js 0.12. closes #193 ([9c38374142d3929be3c9314b5e9bc5d963c5955f](https://github.com/auth0/node-jsonwebtoken/commit/9c38374142d3929be3c9314b5e9bc5d963c5955f)), closes [#193](https://github.com/auth0/node-jsonwebtoken/issues/193)
- improve async test ([7b0981380ddc40a5f1208df520631785b5ffb85a](https://github.com/auth0/node-jsonwebtoken/commit/7b0981380ddc40a5f1208df520631785b5ffb85a))
## 6.1.0 - 2016-04-27
- verify unsigned tokens ([ec880791c10ed5ef7c8df7bf28ebb95c810479ed](https://github.com/auth0/node-jsonwebtoken/commit/ec880791c10ed5ef7c8df7bf28ebb95c810479ed))
## 6.0.1 - 2016-04-27
This was an immediate change after publishing 6.0.0.
- throw error on invalid options when the payload is not an object ([304f1b33075f79ed66f784e27dc4f5307aa39e27](https://github.com/auth0/node-jsonwebtoken/commit/304f1b33075f79ed66f784e27dc4f5307aa39e27))
## 6.0.0 - 2016-04-27
- Change .sign to standard async callback ([50873c7d45d2733244d5da8afef3d1872e657a60](https://github.com/auth0/node-jsonwebtoken/commit/50873c7d45d2733244d5da8afef3d1872e657a60))
- Improved the options for the `sign` method ([53c3987b3cc34e95eb396b26fc9b051276e2f6f9](https://github.com/auth0/node-jsonwebtoken/commit/53c3987b3cc34e95eb396b26fc9b051276e2f6f9))
- throw error on invalid options like `expiresIn` when the payload is not an object ([304f1b33075f79ed66f784e27dc4f5307aa39e27](https://github.com/auth0/node-jsonwebtoken/commit/304f1b33075f79ed66f784e27dc4f5307aa39e27))
- `expiresInMinutes` and `expiresInSeconds` are deprecated and no longer supported.
- `notBeforeInMinutes` and `notBeforeInSeconds` are deprecated and no longer supported.
- `options` are strongly validated.
- `options.expiresIn`, `options.notBefore`, `options.audience`, `options.issuer`, `options.subject` and `options.jwtid` are mutually exclusive with `payload.exp`, `payload.nbf`, `payload.aud`, `payload.iss`
- `options.algorithm` is properly validated.
- `options.headers` is renamed to `options.header`.
- update CHANGELOG to reflect most of the changes. closes #136 ([b87a1a8d2e2533fbfab518765a54f00077918eb7](https://github.com/auth0/node-jsonwebtoken/commit/b87a1a8d2e2533fbfab518765a54f00077918eb7)), closes [#136](https://github.com/auth0/node-jsonwebtoken/issues/136)
- update readme ([53a88ecf4494e30e1d62a1cf3cc354650349f486](https://github.com/auth0/node-jsonwebtoken/commit/53a88ecf4494e30e1d62a1cf3cc354650349f486))
## 5.7.0 - 2016-02-16
- add support for validating multiples issuers. closes #163 ([39d9309ae05648dbd72e5fd1993df064ad0e8fa5](https://github.com/auth0/node-jsonwebtoken/commit/39d9309ae05648dbd72e5fd1993df064ad0e8fa5)), closes [#163](https://github.com/auth0/node-jsonwebtoken/issues/163)
## 5.6.1 - 2016-02-16
- 5.6.1 ([06d8209d499dbc9a8dd978ab6cbb9c6818fde203](https://github.com/auth0/node-jsonwebtoken/commit/06d8209d499dbc9a8dd978ab6cbb9c6818fde203))
- fix wrong error when setting expiration on non-object payload. closes #153 ([7f7d76edfd918d6afc7c7cead888caa42ccaceb4](https://github.com/auth0/node-jsonwebtoken/commit/7f7d76edfd918d6afc7c7cead888caa42ccaceb4)), closes [#153](https://github.com/auth0/node-jsonwebtoken/issues/153)
## 5.6.0 - 2016-02-16
- added missing validations of sub and jti ([a1affe960d0fc52e9042bcbdedb65734f8855580](https://github.com/auth0/node-jsonwebtoken/commit/a1affe960d0fc52e9042bcbdedb65734f8855580))
- Fix tests in jwt.rs.tests.js which causes 4 to fail ([8aedf2b1f575b0d9575c1fc9f2ac7bc868f75ff1](https://github.com/auth0/node-jsonwebtoken/commit/8aedf2b1f575b0d9575c1fc9f2ac7bc868f75ff1))
- Update README.md ([349b7cd00229789b138928ca060d3ef015aedaf9](https://github.com/auth0/node-jsonwebtoken/commit/349b7cd00229789b138928ca060d3ef015aedaf9))
## 5.5.4 - 2016-01-04
- minor ([46552e7c45025c76e3f647680d7539a66bfac612](https://github.com/auth0/node-jsonwebtoken/commit/46552e7c45025c76e3f647680d7539a66bfac612))
## 5.5.3 - 2016-01-04
- add a console.warn on invalid options for string payloads ([71200f14deba0533d3261266348338fac2d14661](https://github.com/auth0/node-jsonwebtoken/commit/71200f14deba0533d3261266348338fac2d14661))
- minor ([65b1f580382dc58dd3da6f47a52713776fd7cdf2](https://github.com/auth0/node-jsonwebtoken/commit/65b1f580382dc58dd3da6f47a52713776fd7cdf2))
## 5.5.2 - 2016-01-04
- fix signing method with sealed objects, do not modify the params object. closes #147 ([be9c09af83b09c9e72da8b2c6166fa51d92aeab6](https://github.com/auth0/node-jsonwebtoken/commit/be9c09af83b09c9e72da8b2c6166fa51d92aeab6)), closes [#147](https://github.com/auth0/node-jsonwebtoken/issues/147)
## 5.5.1 - 2016-01-04
- fix nbf verification. fix #152 ([786d37b299c67771b5e71a2ca476666ab0f97d98](https://github.com/auth0/node-jsonwebtoken/commit/786d37b299c67771b5e71a2ca476666ab0f97d98)), closes [#152](https://github.com/auth0/node-jsonwebtoken/issues/152)
## 5.5.0 - 2015-12-28
- improvements to nbf and jti claims ([46372e928f6d2e7398f9b88022ca617d2a3b0699](https://github.com/auth0/node-jsonwebtoken/commit/46372e928f6d2e7398f9b88022ca617d2a3b0699))
- Remove duplicate payload line (fix bug in IE strict mode) ([8163d698e0c5ad8c44817a5dcd42a15d7e9c6bc8](https://github.com/auth0/node-jsonwebtoken/commit/8163d698e0c5ad8c44817a5dcd42a15d7e9c6bc8))
- Remove duplicate require('ms') line ([7c00bcbcbf8f7503a1070b394a165eccd41de66f](https://github.com/auth0/node-jsonwebtoken/commit/7c00bcbcbf8f7503a1070b394a165eccd41de66f))
- Update README to reflect addition of async sign ([d661d4b6f68eb417834c99b36769444723041ccf](https://github.com/auth0/node-jsonwebtoken/commit/d661d4b6f68eb417834c99b36769444723041ccf))
## 5.4.0 - 2015-10-02
- deprecate expireInMinutes and expireInSeconds - in favor of expiresIn ([39ecc6f8f310f8462e082f1d53de0b4222b29b6f](https://github.com/auth0/node-jsonwebtoken/commit/39ecc6f8f310f8462e082f1d53de0b4222b29b6f))
## 5.3.0 - 2015-10-02
- 5.3.0 ([5d559ced3fbf10c1adae2e5792deda06ea89bcd3](https://github.com/auth0/node-jsonwebtoken/commit/5d559ced3fbf10c1adae2e5792deda06ea89bcd3))
- minor ([6e81ff87a3799b0e56db09cbae42a97e784716c4](https://github.com/auth0/node-jsonwebtoken/commit/6e81ff87a3799b0e56db09cbae42a97e784716c4))
## 5.1.0 - 2015-10-02
- added async signing ([9414fbcb15a1f9cf4fe147d070e9424c547dabba](https://github.com/auth0/node-jsonwebtoken/commit/9414fbcb15a1f9cf4fe147d070e9424c547dabba))
- Update README.md ([40b2aaaa843442dfb8ee7b574f0a788177e7c904](https://github.com/auth0/node-jsonwebtoken/commit/40b2aaaa843442dfb8ee7b574f0a788177e7c904))
## 5.0.5 - 2015-08-19
- add ms dep to package.json ([f13b3fb7f29dff787e7c91ebe2eb5adeeb05f251](https://github.com/auth0/node-jsonwebtoken/commit/f13b3fb7f29dff787e7c91ebe2eb5adeeb05f251))
- add note to explain, related to #96 #101 #6 ([dd8969e0e6ed0bcb9cae905d2b1a96476bd85da3](https://github.com/auth0/node-jsonwebtoken/commit/dd8969e0e6ed0bcb9cae905d2b1a96476bd85da3))
- add tests for options.headers ([7787dd74e705787c39a871ca29c75a2e0a3948ac](https://github.com/auth0/node-jsonwebtoken/commit/7787dd74e705787c39a871ca29c75a2e0a3948ac))
- add tests for verify expires ([d7c5793d98c300603440ab460c11665f661ad3a0](https://github.com/auth0/node-jsonwebtoken/commit/d7c5793d98c300603440ab460c11665f661ad3a0))
- add verify option maxAge (with tests) ([49d54e54f7e70b1c53a2e4ee67e116c907d75319](https://github.com/auth0/node-jsonwebtoken/commit/49d54e54f7e70b1c53a2e4ee67e116c907d75319))
- fix spelling error in error message ([8078b11b224fa05ac9003ca5aa2c85e9f0128cfb](https://github.com/auth0/node-jsonwebtoken/commit/8078b11b224fa05ac9003ca5aa2c85e9f0128cfb))
- Fix typo options.header is not a documented option + ([5feaa5b962ccbddeff054817a410f7b0c1e6ce7f](https://github.com/auth0/node-jsonwebtoken/commit/5feaa5b962ccbddeff054817a410f7b0c1e6ce7f))
- update JWT spec link. closes #112 ([f5fa50f797456a12240589161835c7ea30807195](https://github.com/auth0/node-jsonwebtoken/commit/f5fa50f797456a12240589161835c7ea30807195)), closes [#112](https://github.com/auth0/node-jsonwebtoken/issues/112)
## 5.0.3 - 2015-07-15
- Added nbf support ([f26ba4e2fa197a20497632b63ffcd13ae93aacc4](https://github.com/auth0/node-jsonwebtoken/commit/f26ba4e2fa197a20497632b63ffcd13ae93aacc4))
- Added support for subject and jwt id ([ab76ec5bc554e2d1e25376ddb7cea711d86af651](https://github.com/auth0/node-jsonwebtoken/commit/ab76ec5bc554e2d1e25376ddb7cea711d86af651))
- Fix `this` referring to the global object instead of `module.exports` in `verify()` ([93f554312e37129027fcf4916f48cb8d1b53588c](https://github.com/auth0/node-jsonwebtoken/commit/93f554312e37129027fcf4916f48cb8d1b53588c))
- Fix typo, line 139 README, complete option for .decode. ([59c110aeb8c7c1847ef2ffd77702d13627c89e10](https://github.com/auth0/node-jsonwebtoken/commit/59c110aeb8c7c1847ef2ffd77702d13627c89e10))
- minor ([61ff1172272b582902313e958058ff22413494af](https://github.com/auth0/node-jsonwebtoken/commit/61ff1172272b582902313e958058ff22413494af))
## 5.0.2 - 2015-06-15
- fix typo in docs . closes #86 ([3d3413221f36acef4dfd1cbed87f1f3565cd6f84](https://github.com/auth0/node-jsonwebtoken/commit/3d3413221f36acef4dfd1cbed87f1f3565cd6f84)), closes [#86](https://github.com/auth0/node-jsonwebtoken/issues/86)
## 5.0.1 - 2015-05-15
- Add option to return header and payload when decoding. ([7254e011b59f892d1947e6c11819281adac7069d](https://github.com/auth0/node-jsonwebtoken/commit/7254e011b59f892d1947e6c11819281adac7069d))
- Avoid uncaught "SyntaxError: Unexpected token ͧ" error. ([0dc59cd6ee15d83a606acffa7909ee76176ae186](https://github.com/auth0/node-jsonwebtoken/commit/0dc59cd6ee15d83a606acffa7909ee76176ae186))
- Document complete option in README. ([ec32b20241a74d9681ea26e1a7024b4642468c00](https://github.com/auth0/node-jsonwebtoken/commit/ec32b20241a74d9681ea26e1a7024b4642468c00))
- Fix example in README, silence verbose logging. ([ba3174d10033c41e9c211a38f1cc67f74fbd7f69](https://github.com/auth0/node-jsonwebtoken/commit/ba3174d10033c41e9c211a38f1cc67f74fbd7f69))
- Fix link to auth0.com in README ([1b3c5ff72c9bc25e9271646e679f3080f2a042a0](https://github.com/auth0/node-jsonwebtoken/commit/1b3c5ff72c9bc25e9271646e679f3080f2a042a0))
- Immediate return if not decoded. ([851bda2b10168f3269c3da6e74d310742f31a193](https://github.com/auth0/node-jsonwebtoken/commit/851bda2b10168f3269c3da6e74d310742f31a193))
- Prevent throw on undefined/null secret ([0fdf78d4dbf609455f3277d6169a987aef0384d4](https://github.com/auth0/node-jsonwebtoken/commit/0fdf78d4dbf609455f3277d6169a987aef0384d4))
- Removed path from test ([d6240e24186732d368bffe21143becf44c38f0d6](https://github.com/auth0/node-jsonwebtoken/commit/d6240e24186732d368bffe21143becf44c38f0d6))
- Simplified checking for missing key ([f1cffd033bffc44f20558eda4a797c3fa2f4ee05](https://github.com/auth0/node-jsonwebtoken/commit/f1cffd033bffc44f20558eda4a797c3fa2f4ee05))
- Typo ([ffe68dbe0219bab535c1018448eb4c0b22f1f902](https://github.com/auth0/node-jsonwebtoken/commit/ffe68dbe0219bab535c1018448eb4c0b22f1f902))
- Update CHANGELOG.md ([927cce0dad1bc9aad75aeef53e276cf4cfc0d776](https://github.com/auth0/node-jsonwebtoken/commit/927cce0dad1bc9aad75aeef53e276cf4cfc0d776))
- Update CHANGELOG.md ([6879e0fdde222995c70a3a69a4af94993d9c667e](https://github.com/auth0/node-jsonwebtoken/commit/6879e0fdde222995c70a3a69a4af94993d9c667e))
- Update CHANGELOG.md ([c5596c10e8705727fa13e0394184a606083078bc](https://github.com/auth0/node-jsonwebtoken/commit/c5596c10e8705727fa13e0394184a606083078bc))
- Update CHANGELOG.md ([07541f0315f26d179e1cde92732b6124d6869b6f](https://github.com/auth0/node-jsonwebtoken/commit/07541f0315f26d179e1cde92732b6124d6869b6f))
- Update CHANGELOG.md ([e6465d48ddd1dc2c3297229b28c78fd5490a2ba9](https://github.com/auth0/node-jsonwebtoken/commit/e6465d48ddd1dc2c3297229b28c78fd5490a2ba9))
## [5.0.0] - 2015-04-11
### Changed
- [sign] Only set defautl `iat` if the user does not specify that argument.
https://github.com/auth0/node-jsonwebtoken/commit/e900282a8d2dff1d4dec815f7e6aa7782e867d91
https://github.com/auth0/node-jsonwebtoken/commit/35036b188b4ee6b42df553bbb93bc8a6b19eae9d
https://github.com/auth0/node-jsonwebtoken/commit/954bd7a312934f03036b6bb6f00edd41f29e54d9
https://github.com/auth0/node-jsonwebtoken/commit/24a370080e0b75f11d4717cd2b11b2949d95fc2e
https://github.com/auth0/node-jsonwebtoken/commit/a77df6d49d4ec688dfd0a1cc723586bffe753516
### Security
- [verify] Update to jws@^3.0.0 and renaming `header.alg` mismatch exception to `invalid algorithm` and adding more mismatch tests.
As `jws@3.0.0` changed the verify method signature to be `jws.verify(signature, algorithm, secretOrKey)`, the token header must be decoded first in order to make sure that the `alg` field matches one of the allowed `options.algorithms`. After that, the now validated `header.alg` is passed to `jws.verify`
As the order of steps has changed, the error that was thrown when the JWT was invalid is no longer the `jws` one:
```
{ [Error: Invalid token: no header in signature 'a.b.c'] code: 'MISSING_HEADER', signature: 'a.b.c' }
```
That old error (removed from jws) has been replaced by a `JsonWebTokenError` with message `invalid token`.
> Important: versions >= 4.2.2 this library are safe to use but we decided to deprecate everything `< 5.0.0` to prevent security warnings from library `node-jws` when doing `npm install`.
https://github.com/auth0/node-jsonwebtoken/commit/634b8ed0ff5267dc25da5c808634208af109824e
https://github.com/auth0/node-jsonwebtoken/commit/9f24ffd5791febb449d4d03ff58d7807da9b9b7e
https://github.com/auth0/node-jsonwebtoken/commit/19e6cc6a1f2fd90356f89b074223b9665f2aa8a2
https://github.com/auth0/node-jsonwebtoken/commit/1e4623420159c6410616f02a44ed240f176287a9
https://github.com/auth0/node-jsonwebtoken/commit/954bd7a312934f03036b6bb6f00edd41f29e54d9
https://github.com/auth0/node-jsonwebtoken/commit/24a370080e0b75f11d4717cd2b11b2949d95fc2e
https://github.com/auth0/node-jsonwebtoken/commit/a77df6d49d4ec688dfd0a1cc723586bffe753516
## [4.2.2] - 2015-03-26
### Fixed
- [asymmetric-keys] Fix verify for RSAPublicKey formated keys (`jfromaniello - awlayton`)
https://github.com/auth0/node-jsonwebtoken/commit/402794663b9521bf602fcc6f2e811e7d3912f9dc
https://github.com/auth0/node-jsonwebtoken/commit/8df6aabbc7e1114c8fb3917931078254eb52c222
## [4.2.1] - 2015-03-17
### Fixed
- [asymmetric-keys] Fixed issue when public key starts with BEING PUBLIC KEY (https://github.com/auth0/node-jsonwebtoken/issues/70) (`jfromaniello`)
https://github.com/auth0/node-jsonwebtoken/commit/7017e74db9b194448ff488b3e16468ada60c4ee5
## [4.2.0] - 2015-03-16
### Security
- [asymmetric-keys] Making sure a token signed with an asymmetric key will be verified using a asymmetric key.
When the verification part was expecting a token digitally signed with an asymmetric key (RS/ES family) of algorithms an attacker could send a token signed with a symmetric algorithm (HS* family).
The issue was caused because the same signature was used to verify both type of tokens (`verify` method parameter: `secretOrPublicKey`).
This change adds a new parameter to the verify called `algorithms`. This can be used to specify a list of supported algorithms, but the default value depends on the secret used: if the secretOrPublicKey contains the string `BEGIN CERTIFICATE` the default is `[ 'RS256','RS384','RS512','ES256','ES384','ES512' ]` otherwise is `[ 'HS256','HS384','HS512' ]`. (`jfromaniello`)
https://github.com/auth0/node-jsonwebtoken/commit/c2bf7b2cd7e8daf66298c2d168a008690bc4bdd3
https://github.com/auth0/node-jsonwebtoken/commit/1bb584bc382295eeb7ee8c4452a673a77a68b687
## [4.1.0] - 2015-03-10
### Changed
- Assume the payload is JSON even when there is no `typ` property. [5290db1](https://github.com/auth0/node-jsonwebtoken/commit/5290db1bd74f74cd38c90b19e2355ef223a4d931)
## [4.0.0] - 2015-03-06
### Changed
- The default encoding is now utf8 instead of binary. [92d33bd](https://github.com/auth0/node-jsonwebtoken/commit/92d33bd99a3416e9e5a8897d9ad8ff7d70a00bfd)
- Add `encoding` as a new option to `sign`. [1fc385e](https://github.com/auth0/node-jsonwebtoken/commit/1fc385ee10bd0018cd1441552dce6c2e5a16375f)
- Add `ignoreExpiration` to `verify`. [8d4da27](https://github.com/auth0/node-jsonwebtoken/commit/8d4da279e1b351ac71ace276285c9255186d549f)
- Add `expiresInSeconds` to `sign`. [dd156cc](https://github.com/auth0/node-jsonwebtoken/commit/dd156cc30f17028744e60aec0502897e34609329)
### Fixed
- Fix wrong error message when the audience doesn't match. [44e3c8d](https://github.com/auth0/node-jsonwebtoken/commit/44e3c8d757e6b4e2a57a69a035f26b4abec3e327)
- Fix wrong error message when the issuer doesn't match. [44e3c8d](https://github.com/auth0/node-jsonwebtoken/commit/44e3c8d757e6b4e2a57a69a035f26b4abec3e327)
- Fix wrong `iat` and `exp` values when signing with `noTimestamp`. [331b7bc](https://github.com/auth0/node-jsonwebtoken/commit/331b7bc9cc335561f8806f2c4558e105cb53e0a6)

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Auth0, Inc. <support@auth0.com> (http://auth0.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,371 @@
# jsonwebtoken
| **Build** | **Dependency** |
|-----------|---------------|
| [![Build Status](https://secure.travis-ci.org/auth0/node-jsonwebtoken.svg?branch=master)](http://travis-ci.org/auth0/node-jsonwebtoken) | [![Dependency Status](https://david-dm.org/auth0/node-jsonwebtoken.svg)](https://david-dm.org/auth0/node-jsonwebtoken) |
An implementation of [JSON Web Tokens](https://tools.ietf.org/html/rfc7519).
This was developed against `draft-ietf-oauth-json-web-token-08`. It makes use of [node-jws](https://github.com/brianloveswords/node-jws)
# Install
```bash
$ npm install jsonwebtoken
```
# Migration notes
* [From v7 to v8](https://github.com/auth0/node-jsonwebtoken/wiki/Migration-Notes:-v7-to-v8)
# Usage
### jwt.sign(payload, secretOrPrivateKey, [options, callback])
(Asynchronous) If a callback is supplied, the callback is called with the `err` or the JWT.
(Synchronous) Returns the JsonWebToken as string
`payload` could be an object literal, buffer or string representing valid JSON.
> **Please _note_ that** `exp` or any other claim is only set if the payload is an object literal. Buffer or string payloads are not checked for JSON validity.
> If `payload` is not a buffer or a string, it will be coerced into a string using `JSON.stringify`.
`secretOrPrivateKey` is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM
encoded private key for RSA and ECDSA. In case of a private key with passphrase an object `{ key, passphrase }` can be used (based on [crypto documentation](https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format)), in this case be sure you pass the `algorithm` option.
`options`:
* `algorithm` (default: `HS256`)
* `expiresIn`: expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms).
> Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
* `notBefore`: expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms).
> Eg: `60`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
* `audience`
* `issuer`
* `jwtid`
* `subject`
* `noTimestamp`
* `header`
* `keyid`
* `mutatePayload`: if true, the sign function will modify the payload object directly. This is useful if you need a raw reference to the payload after claims have been applied to it but before it has been encoded into a token.
> There are no default values for `expiresIn`, `notBefore`, `audience`, `subject`, `issuer`. These claims can also be provided in the payload directly with `exp`, `nbf`, `aud`, `sub` and `iss` respectively, but you **_can't_** include in both places.
Remember that `exp`, `nbf` and `iat` are **NumericDate**, see related [Token Expiration (exp claim)](#token-expiration-exp-claim)
The header can be customized via the `options.header` object.
Generated jwts will include an `iat` (issued at) claim by default unless `noTimestamp` is specified. If `iat` is inserted in the payload, it will be used instead of the real timestamp for calculating other things like `exp` given a timespan in `options.expiresIn`.
Synchronous Sign with default (HMAC SHA256)
```js
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
```
Synchronous Sign with RSA SHA256
```js
// sign with RSA SHA256
var cert = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});
```
Sign asynchronously
```js
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {
console.log(token);
});
```
Backdate a jwt 30 seconds
```js
var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh');
```
#### Token Expiration (exp claim)
The standard for JWT defines an `exp` claim for expiration. The expiration is represented as a **NumericDate**:
> A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
This means that the `exp` field should contain the number of seconds since the epoch.
Signing a token with 1 hour of expiration:
```javascript
jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'secret');
```
Another way to generate a token like this with this library is:
```javascript
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
//or even better:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: '1h' });
```
### jwt.verify(token, secretOrPublicKey, [options, callback])
(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.
(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.
`token` is the JsonWebToken string
`secretOrPublicKey` is a string or buffer containing either the secret for HMAC algorithms, or the PEM
encoded public key for RSA and ECDSA.
If `jwt.verify` is called asynchronous, `secretOrPublicKey` can be a function that should fetch the secret or public key. See below for a detailed example
As mentioned in [this comment](https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138), there are other libraries that expect base64 encoded secrets (random bytes encoded using base64), if that is your case you can pass `Buffer.from(secret, 'base64')`, by doing this the secret will be decoded using base64 and the token verification will use the original random bytes.
`options`
* `algorithms`: List of strings with the names of the allowed algorithms. For instance, `["HS256", "HS384"]`.
* `audience`: if you want to check audience (`aud`), provide a value here. The audience can be checked against a string, a regular expression or a list of strings and/or regular expressions.
> Eg: `"urn:foo"`, `/urn:f[o]{2}/`, `[/urn:f[o]{2}/, "urn:bar"]`
* `issuer` (optional): string or array of strings of valid values for the `iss` field.
* `ignoreExpiration`: if `true` do not validate the expiration of the token.
* `ignoreNotBefore`...
* `subject`: if you want to check subject (`sub`), provide a value here
* `clockTolerance`: number of seconds to tolerate when checking the `nbf` and `exp` claims, to deal with small clock differences among different servers
* `maxAge`: the maximum allowed age for tokens to still be valid. It is expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms).
> Eg: `1000`, `"2 days"`, `"10h"`, `"7d"`. A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default (`"120"` is equal to `"120ms"`).
* `clockTimestamp`: the time in seconds that should be used as the current time for all necessary comparisons.
* `nonce`: if you want to check `nonce` claim, provide a string value here. It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes))
```js
// verify a token symmetric - synchronous
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded.foo) // bar
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
}
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
// verify a token asymmetric
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, function(err, decoded) {
console.log(decoded.foo) // bar
});
// verify audience
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
// if audience mismatch, err == invalid audience
});
// verify issuer
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
// if issuer mismatch, err == invalid issuer
});
// verify jwt id
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid' }, function(err, decoded) {
// if jwt id mismatch, err == invalid jwt id
});
// verify subject
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer', jwtid: 'jwtid', subject: 'subject' }, function(err, decoded) {
// if subject mismatch, err == invalid subject
});
// alg mismatch
var cert = fs.readFileSync('public.pem'); // get public key
jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {
// if token alg != RS256, err == invalid signature
});
// Verify using getKey callback
// Example uses https://github.com/auth0/node-jwks-rsa as a way to fetch the keys.
var jwksClient = require('jwks-rsa');
var client = jwksClient({
jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json'
});
function getKey(header, callback){
client.getSigningKey(header.kid, function(err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
callback(null, signingKey);
});
}
jwt.verify(token, getKey, options, function(err, decoded) {
console.log(decoded.foo) // bar
});
```
### jwt.decode(token [, options])
(Synchronous) Returns the decoded payload without verifying if the signature is valid.
> __Warning:__ This will __not__ verify whether the signature is valid. You should __not__ use this for untrusted messages. You most likely want to use `jwt.verify` instead.
`token` is the JsonWebToken string
`options`:
* `json`: force JSON.parse on the payload even if the header doesn't contain `"typ":"JWT"`.
* `complete`: return an object with the decoded payload and header.
Example
```js
// get the decoded payload ignoring signature, no secretOrPrivateKey needed
var decoded = jwt.decode(token);
// get the decoded payload and header
var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload)
```
## Errors & Codes
Possible thrown errors during verification.
Error is the first argument of the verification callback.
### TokenExpiredError
Thrown error if the token is expired.
Error object:
* name: 'TokenExpiredError'
* message: 'jwt expired'
* expiredAt: [ExpDate]
```js
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 1408621000
}
*/
}
});
```
### JsonWebTokenError
Error object:
* name: 'JsonWebTokenError'
* message:
* 'jwt malformed'
* 'jwt signature is required'
* 'invalid signature'
* 'jwt audience invalid. expected: [OPTIONS AUDIENCE]'
* 'jwt issuer invalid. expected: [OPTIONS ISSUER]'
* 'jwt id invalid. expected: [OPTIONS JWT ID]'
* 'jwt subject invalid. expected: [OPTIONS SUBJECT]'
```js
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'JsonWebTokenError',
message: 'jwt malformed'
}
*/
}
});
```
### NotBeforeError
Thrown if current time is before the nbf claim.
Error object:
* name: 'NotBeforeError'
* message: 'jwt not active'
* date: 2018-10-04T16:10:44.000Z
```js
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'NotBeforeError',
message: 'jwt not active',
date: 2018-10-04T16:10:44.000Z
}
*/
}
});
```
## Algorithms supported
Array of supported algorithms. The following algorithms are currently supported.
alg Parameter Value | Digital Signature or MAC Algorithm
----------------|----------------------------
HS256 | HMAC using SHA-256 hash algorithm
HS384 | HMAC using SHA-384 hash algorithm
HS512 | HMAC using SHA-512 hash algorithm
RS256 | RSASSA using SHA-256 hash algorithm
RS384 | RSASSA using SHA-384 hash algorithm
RS512 | RSASSA using SHA-512 hash algorithm
ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm
ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm
ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm
none | No digital signature or MAC value included
## Refreshing JWTs
First of all, we recommend you to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.
We are not comfortable including this as part of the library, however, you can take a look at [this example](https://gist.github.com/ziluvatar/a3feb505c4c0ec37059054537b38fc48) to show how this could be accomplished.
Apart from that example there are [an issue](https://github.com/auth0/node-jsonwebtoken/issues/122) and [a pull request](https://github.com/auth0/node-jsonwebtoken/pull/172) to get more knowledge about this topic.
# TODO
* X.509 certificate chain is not checked
## Issue Reporting
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
## Author
[Auth0](https://auth0.com)
## License
This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.

View File

@@ -0,0 +1,30 @@
var jws = require('jws');
module.exports = function (jwt, options) {
options = options || {};
var decoded = jws.decode(jwt, options);
if (!decoded) { return null; }
var payload = decoded.payload;
//try parse the payload
if(typeof payload === 'string') {
try {
var obj = JSON.parse(payload);
if(obj !== null && typeof obj === 'object') {
payload = obj;
}
} catch (e) { }
}
//return header if `complete` option is enabled. header includes claims
//such as `kid` and `alg` used to select the key within a JWKS needed to
//verify the signature
if (options.complete === true) {
return {
header: decoded.header,
payload: payload,
signature: decoded.signature
};
}
return payload;
};

View File

@@ -0,0 +1,8 @@
module.exports = {
decode: require('./decode'),
verify: require('./verify'),
sign: require('./sign'),
JsonWebTokenError: require('./lib/JsonWebTokenError'),
NotBeforeError: require('./lib/NotBeforeError'),
TokenExpiredError: require('./lib/TokenExpiredError'),
};

View File

@@ -0,0 +1,14 @@
var JsonWebTokenError = function (message, error) {
Error.call(this, message);
if(Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = 'JsonWebTokenError';
this.message = message;
if (error) this.inner = error;
};
JsonWebTokenError.prototype = Object.create(Error.prototype);
JsonWebTokenError.prototype.constructor = JsonWebTokenError;
module.exports = JsonWebTokenError;

View File

@@ -0,0 +1,13 @@
var JsonWebTokenError = require('./JsonWebTokenError');
var NotBeforeError = function (message, date) {
JsonWebTokenError.call(this, message);
this.name = 'NotBeforeError';
this.date = date;
};
NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype);
NotBeforeError.prototype.constructor = NotBeforeError;
module.exports = NotBeforeError;

View File

@@ -0,0 +1,13 @@
var JsonWebTokenError = require('./JsonWebTokenError');
var TokenExpiredError = function (message, expiredAt) {
JsonWebTokenError.call(this, message);
this.name = 'TokenExpiredError';
this.expiredAt = expiredAt;
};
TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype);
TokenExpiredError.prototype.constructor = TokenExpiredError;
module.exports = TokenExpiredError;

View File

@@ -0,0 +1,18 @@
var ms = require('ms');
module.exports = function (time, iat) {
var timestamp = iat || Math.floor(Date.now() / 1000);
if (typeof time === 'string') {
var milliseconds = ms(time);
if (typeof milliseconds === 'undefined') {
return;
}
return Math.floor(timestamp + milliseconds / 1000);
} else if (typeof time === 'number') {
return timestamp + time;
} else {
return;
}
};

View File

@@ -0,0 +1,98 @@
{
"_from": "jsonwebtoken@^8.2.1",
"_id": "jsonwebtoken@8.4.0",
"_inBundle": false,
"_integrity": "sha512-coyXjRTCy0pw5WYBpMvWOMN+Kjaik2MwTUIq9cna/W7NpO9E+iYbumZONAz3hcr+tXFJECoQVrtmIoC3Oz0gvg==",
"_location": "/firebase-functions/jsonwebtoken",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "jsonwebtoken@^8.2.1",
"name": "jsonwebtoken",
"escapedName": "jsonwebtoken",
"rawSpec": "^8.2.1",
"saveSpec": null,
"fetchSpec": "^8.2.1"
},
"_requiredBy": [
"/firebase-functions"
],
"_resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.4.0.tgz",
"_shasum": "8757f7b4cb7440d86d5e2f3becefa70536c8e46a",
"_spec": "jsonwebtoken@^8.2.1",
"_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\firebase-functions",
"author": {
"name": "auth0"
},
"bugs": {
"url": "https://github.com/auth0/node-jsonwebtoken/issues"
},
"bundleDependencies": false,
"dependencies": {
"jws": "^3.1.5",
"lodash.includes": "^4.3.0",
"lodash.isboolean": "^3.0.3",
"lodash.isinteger": "^4.0.4",
"lodash.isnumber": "^3.0.3",
"lodash.isplainobject": "^4.0.6",
"lodash.isstring": "^4.0.1",
"lodash.once": "^4.0.0",
"ms": "^2.1.1"
},
"deprecated": false,
"description": "JSON Web Token implementation (symmetric and asymmetric)",
"devDependencies": {
"atob": "^2.1.2",
"chai": "^4.1.2",
"conventional-changelog": "~1.1.0",
"cost-of-modules": "^1.0.1",
"eslint": "^4.19.1",
"mocha": "^5.2.0",
"nsp": "^2.6.2",
"nyc": "^11.9.0",
"sinon": "^6.0.0"
},
"engines": {
"node": ">=4",
"npm": ">=1.4.28"
},
"files": [
"lib",
"decode.js",
"sign.js",
"verify.js"
],
"homepage": "https://github.com/auth0/node-jsonwebtoken#readme",
"keywords": [
"jwt"
],
"license": "MIT",
"main": "index.js",
"name": "jsonwebtoken",
"nyc": {
"check-coverage": true,
"lines": 95,
"statements": 95,
"functions": 100,
"branches": 95,
"exclude": [
"./test/**"
],
"reporter": [
"json",
"lcov",
"text-summary"
]
},
"repository": {
"type": "git",
"url": "git+https://github.com/auth0/node-jsonwebtoken.git"
},
"scripts": {
"coverage": "nyc mocha",
"lint": "eslint .",
"test": "npm run lint && npm run coverage && nsp check && cost-of-modules"
},
"version": "8.4.0"
}

View File

@@ -0,0 +1,200 @@
var timespan = require('./lib/timespan');
var jws = require('jws');
var includes = require('lodash.includes');
var isBoolean = require('lodash.isboolean');
var isInteger = require('lodash.isinteger');
var isNumber = require('lodash.isnumber');
var isPlainObject = require('lodash.isplainobject');
var isString = require('lodash.isstring');
var once = require('lodash.once');
var sign_options_schema = {
expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' },
notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' },
audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' },
algorithm: { isValid: includes.bind(null, ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none']), message: '"algorithm" must be a valid string enum value' },
header: { isValid: isPlainObject, message: '"header" must be an object' },
encoding: { isValid: isString, message: '"encoding" must be a string' },
issuer: { isValid: isString, message: '"issuer" must be a string' },
subject: { isValid: isString, message: '"subject" must be a string' },
jwtid: { isValid: isString, message: '"jwtid" must be a string' },
noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' },
keyid: { isValid: isString, message: '"keyid" must be a string' },
mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' }
};
var registered_claims_schema = {
iat: { isValid: isNumber, message: '"iat" should be a number of seconds' },
exp: { isValid: isNumber, message: '"exp" should be a number of seconds' },
nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' }
};
function validate(schema, allowUnknown, object, parameterName) {
if (!isPlainObject(object)) {
throw new Error('Expected "' + parameterName + '" to be a plain object.');
}
Object.keys(object)
.forEach(function(key) {
var validator = schema[key];
if (!validator) {
if (!allowUnknown) {
throw new Error('"' + key + '" is not allowed in "' + parameterName + '"');
}
return;
}
if (!validator.isValid(object[key])) {
throw new Error(validator.message);
}
});
}
function validateOptions(options) {
return validate(sign_options_schema, false, options, 'options');
}
function validatePayload(payload) {
return validate(registered_claims_schema, true, payload, 'payload');
}
var options_to_payload = {
'audience': 'aud',
'issuer': 'iss',
'subject': 'sub',
'jwtid': 'jti'
};
var options_for_objects = [
'expiresIn',
'notBefore',
'noTimestamp',
'audience',
'issuer',
'subject',
'jwtid',
];
module.exports = function (payload, secretOrPrivateKey, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
} else {
options = options || {};
}
var isObjectPayload = typeof payload === 'object' &&
!Buffer.isBuffer(payload);
var header = Object.assign({
alg: options.algorithm || 'HS256',
typ: isObjectPayload ? 'JWT' : undefined,
kid: options.keyid
}, options.header);
function failure(err) {
if (callback) {
return callback(err);
}
throw err;
}
if (!secretOrPrivateKey && options.algorithm !== 'none') {
return failure(new Error('secretOrPrivateKey must have a value'));
}
if (typeof payload === 'undefined') {
return failure(new Error('payload is required'));
} else if (isObjectPayload) {
try {
validatePayload(payload);
}
catch (error) {
return failure(error);
}
if (!options.mutatePayload) {
payload = Object.assign({},payload);
}
} else {
var invalid_options = options_for_objects.filter(function (opt) {
return typeof options[opt] !== 'undefined';
});
if (invalid_options.length > 0) {
return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload'));
}
}
if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') {
return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));
}
if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') {
return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));
}
try {
validateOptions(options);
}
catch (error) {
return failure(error);
}
var timestamp = payload.iat || Math.floor(Date.now() / 1000);
if (!options.noTimestamp) {
payload.iat = timestamp;
} else {
delete payload.iat;
}
if (typeof options.notBefore !== 'undefined') {
try {
payload.nbf = timespan(options.notBefore, timestamp);
}
catch (err) {
return failure(err);
}
if (typeof payload.nbf === 'undefined') {
return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
}
if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
try {
payload.exp = timespan(options.expiresIn, timestamp);
}
catch (err) {
return failure(err);
}
if (typeof payload.exp === 'undefined') {
return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
}
Object.keys(options_to_payload).forEach(function (key) {
var claim = options_to_payload[key];
if (typeof options[key] !== 'undefined') {
if (typeof payload[claim] !== 'undefined') {
return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.'));
}
payload[claim] = options[key];
}
});
var encoding = options.encoding || 'utf8';
if (typeof callback === 'function') {
callback = callback && once(callback);
jws.createSign({
header: header,
privateKey: secretOrPrivateKey,
payload: payload,
encoding: encoding
}).once('error', callback)
.once('done', function (signature) {
callback(null, signature);
});
} else {
return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
}
};

View File

@@ -0,0 +1,208 @@
var JsonWebTokenError = require('./lib/JsonWebTokenError');
var NotBeforeError = require('./lib/NotBeforeError');
var TokenExpiredError = require('./lib/TokenExpiredError');
var decode = require('./decode');
var timespan = require('./lib/timespan');
var jws = require('jws');
module.exports = function (jwtString, secretOrPublicKey, options, callback) {
if ((typeof options === 'function') && !callback) {
callback = options;
options = {};
}
if (!options) {
options = {};
}
//clone this object since we are going to mutate it.
options = Object.assign({}, options);
var done;
if (callback) {
done = callback;
} else {
done = function(err, data) {
if (err) throw err;
return data;
};
}
if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') {
return done(new JsonWebTokenError('clockTimestamp must be a number'));
}
if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) {
return done(new JsonWebTokenError('nonce must be a non-empty string'));
}
var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000);
if (!jwtString){
return done(new JsonWebTokenError('jwt must be provided'));
}
if (typeof jwtString !== 'string') {
return done(new JsonWebTokenError('jwt must be a string'));
}
var parts = jwtString.split('.');
if (parts.length !== 3){
return done(new JsonWebTokenError('jwt malformed'));
}
var decodedToken;
try {
decodedToken = decode(jwtString, { complete: true });
} catch(err) {
return done(err);
}
if (!decodedToken) {
return done(new JsonWebTokenError('invalid token'));
}
var header = decodedToken.header;
var getSecret;
if(typeof secretOrPublicKey === 'function') {
if(!callback) {
return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback'));
}
getSecret = secretOrPublicKey;
}
else {
getSecret = function(header, secretCallback) {
return secretCallback(null, secretOrPublicKey);
};
}
return getSecret(header, function(err, secretOrPublicKey) {
if(err) {
return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message));
}
var hasSignature = parts[2].trim() !== '';
if (!hasSignature && secretOrPublicKey){
return done(new JsonWebTokenError('jwt signature is required'));
}
if (hasSignature && !secretOrPublicKey) {
return done(new JsonWebTokenError('secret or public key must be provided'));
}
if (!hasSignature && !options.algorithms) {
options.algorithms = ['none'];
}
if (!options.algorithms) {
options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') ||
~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ?
['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512'] :
~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ?
['RS256', 'RS384', 'RS512'] :
['HS256', 'HS384', 'HS512'];
}
if (!~options.algorithms.indexOf(decodedToken.header.alg)) {
return done(new JsonWebTokenError('invalid algorithm'));
}
var valid;
try {
valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey);
} catch (e) {
return done(e);
}
if (!valid) {
return done(new JsonWebTokenError('invalid signature'));
}
var payload = decodedToken.payload;
if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {
if (typeof payload.nbf !== 'number') {
return done(new JsonWebTokenError('invalid nbf value'));
}
if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) {
return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
}
}
if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {
if (typeof payload.exp !== 'number') {
return done(new JsonWebTokenError('invalid exp value'));
}
if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) {
return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));
}
}
if (options.audience) {
var audiences = Array.isArray(options.audience) ? options.audience : [options.audience];
var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
var match = target.some(function (targetAudience) {
return audiences.some(function (audience) {
return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience;
});
});
if (!match) {
return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));
}
}
if (options.issuer) {
var invalid_issuer =
(typeof options.issuer === 'string' && payload.iss !== options.issuer) ||
(Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);
if (invalid_issuer) {
return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));
}
}
if (options.subject) {
if (payload.sub !== options.subject) {
return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));
}
}
if (options.jwtid) {
if (payload.jti !== options.jwtid) {
return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));
}
}
if (options.nonce) {
if (payload.nonce !== options.nonce) {
return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce));
}
}
if (options.maxAge) {
if (typeof payload.iat !== 'number') {
return done(new JsonWebTokenError('iat required when maxAge is specified'));
}
var maxAgeTimestamp = timespan(options.maxAge, payload.iat);
if (typeof maxAgeTimestamp === 'undefined') {
return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));
}
if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) {
return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000)));
}
}
return done(null, payload);
});
};

View File

@@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,69 @@
{
"_from": "ms@^2.1.1",
"_id": "ms@2.1.1",
"_inBundle": false,
"_integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==",
"_location": "/firebase-functions/ms",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ms@^2.1.1",
"name": "ms",
"escapedName": "ms",
"rawSpec": "^2.1.1",
"saveSpec": null,
"fetchSpec": "^2.1.1"
},
"_requiredBy": [
"/firebase-functions/jsonwebtoken"
],
"_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"_shasum": "30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a",
"_spec": "ms@^2.1.1",
"_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions\\node_modules\\firebase-functions\\node_modules\\jsonwebtoken",
"bugs": {
"url": "https://github.com/zeit/ms/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Tiny millisecond conversion utility",
"devDependencies": {
"eslint": "4.12.1",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"files": [
"index.js"
],
"homepage": "https://github.com/zeit/ms#readme",
"license": "MIT",
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"main": "./index",
"name": "ms",
"repository": {
"type": "git",
"url": "git+https://github.com/zeit/ms.git"
},
"scripts": {
"lint": "eslint lib/* bin/*",
"precommit": "lint-staged",
"test": "mocha tests.js"
},
"version": "2.1.1"
}

View File

@@ -0,0 +1,60 @@
# ms
[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

View File

@@ -0,0 +1,105 @@
{
"_from": "firebase-functions@^2.1.0",
"_id": "firebase-functions@2.1.0",
"_inBundle": false,
"_integrity": "sha512-gvWjfIu/q0jXSE/4JY+6XZyJWVzk0TeGLJAfKE4Y7W/cUxkycogc7EIBJSEMdHnxFAD3GE6VgCrhtTTmUud6Sw==",
"_location": "/firebase-functions",
"_phantomChildren": {
"jws": "3.1.5",
"lodash.includes": "4.3.0",
"lodash.isboolean": "3.0.3",
"lodash.isinteger": "4.0.4",
"lodash.isnumber": "3.0.3",
"lodash.isplainobject": "4.0.6",
"lodash.isstring": "4.0.1",
"lodash.once": "4.1.1"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "firebase-functions@^2.1.0",
"name": "firebase-functions",
"escapedName": "firebase-functions",
"rawSpec": "^2.1.0",
"saveSpec": null,
"fetchSpec": "^2.1.0"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/firebase-functions/-/firebase-functions-2.1.0.tgz",
"_shasum": "10973f9055092aaa8ed5bd26410426a9790a99ea",
"_spec": "firebase-functions@^2.1.0",
"_where": "C:\\Users\\jlevi\\Downloads\\tr2022-strategy-master\\tr2022-strategy-master\\data analysis\\functions",
"author": {
"name": "Firebase Team"
},
"bugs": {
"url": "https://github.com/firebase/firebase-functions/issues"
},
"bundleDependencies": false,
"dependencies": {
"@types/cors": "^2.8.1",
"@types/express": "^4.11.1",
"@types/jsonwebtoken": "^7.2.6",
"@types/lodash": "^4.14.34",
"cors": "^2.8.4",
"express": "^4.16.2",
"jsonwebtoken": "^8.2.1",
"lodash": "^4.6.1"
},
"deprecated": false,
"description": "Firebase SDK for Cloud Functions",
"devDependencies": {
"@types/chai": "^3.4.32",
"@types/chai-as-promised": "0.0.28",
"@types/mocha": "^5.2.5",
"@types/mock-require": "^1.3.3",
"@types/nock": "^0.54.32",
"@types/node": "^6.0.38",
"@types/sinon": "^1.16.29",
"chai": "^3.5.0",
"chai-as-promised": "^5.2.0",
"firebase-admin": "~6.0.0",
"istanbul": "^0.4.2",
"mocha": "^5.2.0",
"mock-require": "^2.0.1",
"nock": "^9.0.0",
"prettier": "^1.13.7",
"sinon": "^1.17.4",
"typescript": "~2.8.3"
},
"engines": {
"node": ">=6.0.0"
},
"homepage": "https://github.com/firebase/firebase-functions#readme",
"keywords": [
"firebase",
"functions",
"google",
"cloud"
],
"license": "MIT",
"main": "lib/index.js",
"name": "firebase-functions",
"peerDependencies": {
"firebase-admin": "~6.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/firebase/firebase-functions.git"
},
"scripts": {
"build": "tsc -p tsconfig.release.json",
"build:pack": "rm -rf lib && npm install && node_modules/.bin/tsc -p tsconfig.release.json && npm pack",
"build:release": "npm install --production && npm install typescript firebase-admin && node_modules/.bin/tsc -p tsconfig.release.json",
"format": "prettier --write '**/*.ts'",
"mocha": "mocha .tmp/spec/index.spec.js",
"postinstall": "node ./upgrade-warning",
"posttest": "npm run format && rm -rf .tmp",
"pretest": "tsc && cp -r spec/fixtures .tmp/spec",
"test": "npm run mocha"
},
"typings": "lib/index.d.ts",
"version": "2.1.0"
}

View File

@@ -0,0 +1,15 @@
#!/usr/bin/env node
'use strict';
const message = `
======== WARNING! ========
This upgrade of firebase-functions contains breaking changes if you are upgrading from a version below v1.0.0.
To see a complete list of these breaking changes, please go to:
https://firebase.google.com/docs/functions/beta-v1-diff
`;
console.log(message);