Skip to content

Commit 11f7c24

Browse files
authored
Merge pull request #17 from xhoms/master
bump to version v0.2
2 parents ab63b50 + 0290c00 commit 11f7c24

93 files changed

Lines changed: 6107 additions & 2011 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ package-lock.json
22
secrets.*
33
example/*js
44
lib/*js
5-
node_modules/
5+
node_modules/
6+
extras/

dist/autocredentials.d.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { CredentialProviderOptions } from './credentialprovider';
2+
import { DevTokenCredentialsOptions } from './devtokencredentials';
3+
import { Credentials } from './credentials';
4+
import { EntryPoint } from './common';
5+
export declare function autoCredentials(opt?: CredentialProviderOptions & DevTokenCredentialsOptions & {
6+
accessToken?: string;
7+
refreshToken?: string;
8+
entryPoint?: EntryPoint;
9+
}): Promise<Credentials>;

dist/autocredentials.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"use strict";
2+
// Copyright 2015-2019 Palo Alto Networks, Inc
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
Object.defineProperty(exports, "__esModule", { value: true });
15+
const credentialprovider_1 = require("./credentialprovider");
16+
const devtokencredentials_1 = require("./devtokencredentials");
17+
const credentials_1 = require("./credentials");
18+
const common_1 = require("./common");
19+
const error_1 = require("./error");
20+
const process_1 = require("process");
21+
async function autoCredentials(opt) {
22+
let envClientId = process_1.env['PAN_CLIENT_ID'];
23+
let envClientSecret = process_1.env['PAN_CLIENT_SECRET'];
24+
let envRefreshToken = process_1.env['PAN_REFRESH_TOKEN'];
25+
let envAccessToken = process_1.env['PAN_ACCESS_TOKEN'];
26+
let envEntryPoint = process_1.env['PAN_ENTRYPOINT'];
27+
let entryPoint = 'https://api.us.paloaltonetworks.com';
28+
if (envEntryPoint) {
29+
entryPoint = envEntryPoint;
30+
}
31+
else {
32+
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Environmental variable PAN_ENTRYPOINT not set. Assuming https://api.us.paloaltonetworks.com');
33+
}
34+
if (!(envAccessToken || (envClientId && envClientSecret && envRefreshToken))) {
35+
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Neither "PAN_ACCESS_TOKEN" (for static credentials) nor "PAN_CLIENT_ID", "PAN_CLIENT_SECRET" and "PAN_REFRESH_TOKEN" for a memory-based credentials provider where provider. Will try with developer token credetials');
36+
let devTokCredentias = new devtokencredentials_1.DevTokenCredentials(Object.assign({ entryPoint: entryPoint }, opt));
37+
await devTokCredentias.retrieveAccessToken();
38+
return devTokCredentias;
39+
}
40+
if (envClientId && envClientSecret && envRefreshToken) {
41+
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Using memory based credentials provider');
42+
return credentialprovider_1.defaultCredentialsProviderFactory(Object.assign({ clientId: envClientId, clientSecret: envClientSecret, refreshToken: envRefreshToken, entryPoint: entryPoint }, opt));
43+
}
44+
if (envAccessToken) {
45+
common_1.commonLogger.info({ className: 'AutoCredentials' }, 'Using startic credentials. No refresh available.');
46+
return credentials_1.defaultCredentialsFactory(entryPoint, envAccessToken);
47+
}
48+
throw new error_1.PanCloudError({ className: 'AutoCredentials' }, 'CONFIG', 'Unknown error');
49+
}
50+
exports.autoCredentials = autoCredentials;

dist/common.d.ts

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
/**
22
* Provides common resources for other modules in the pancloud SDK
33
*/
4-
import { sdkErr } from './error';
4+
import { SdkErr } from './error';
55
/**
66
* A pancloud class must provide a className property that will be used to format its log messages
77
*/
8-
export interface pancloudClass {
8+
export interface PancloudClass {
99
className: string;
1010
}
11-
export declare enum logLevel {
11+
export declare enum LogLevel {
1212
DEBUG = 0,
1313
INFO = 1,
1414
ALERT = 2,
@@ -17,12 +17,12 @@ export declare enum logLevel {
1717
/**
1818
* User-provided logger classes are supported as long as they adhere to this interface
1919
*/
20-
export interface pancloudLogger {
21-
level: logLevel;
22-
error(e: sdkErr): void;
23-
alert(source: pancloudClass, message: string, name?: string): void;
24-
info(source: pancloudClass, message: string, name?: string): void;
25-
debug(source: pancloudClass, message: string, name?: string, payload?: any): void;
20+
export interface PancloudLogger {
21+
level: LogLevel;
22+
error(e: SdkErr): void;
23+
alert(source: PancloudClass, message: string, name?: string): void;
24+
info(source: PancloudClass, message: string, name?: string): void;
25+
debug(source: PancloudClass, message: string, name?: string, payload?: any): void;
2626
}
2727
declare const LTYPES: {
2828
"panw.auth": string;
@@ -51,30 +51,31 @@ declare const LTYPES: {
5151
/**
5252
* Convenience type to guide the developer using the right entry points
5353
*/
54-
export declare type ENTRYPOINT = 'https://api.eu.paloaltonetworks.com' | 'https://api.us.paloaltonetworks.com';
55-
/**
56-
* Convenience type to guide the developer using the right paths
57-
*/
58-
export declare type PATH = "event-service/v1/channels" | "logging-service/v1/queries" | "directory-sync-service/v1";
54+
export declare type EntryPoint = 'https://api.eu.paloaltonetworks.com' | 'https://api.us.paloaltonetworks.com';
55+
export declare const region2EntryPoint: {
56+
[region: string]: EntryPoint;
57+
};
58+
export declare type OAUTH2SCOPE = 'logging-service:read' | 'logging-service:write' | 'event-service:read' | 'directory-sync-service:read';
59+
export declare type ApiPath = "event-service/v1/channels" | "logging-service/v1" | "directory-sync-service/v1";
5960
/**
6061
* Convenience type to guide the developer using the common log types
6162
*/
62-
export declare type LOGTYPE = keyof typeof LTYPES;
63-
export declare function isKnownLogType(t: string): t is LOGTYPE;
63+
export declare type LogType = keyof typeof LTYPES;
64+
export declare function isKnownLogType(t: string): t is LogType;
6465
/**
6566
* Instantiate a module-provided logger at load time
6667
*/
67-
export declare let commonLogger: pancloudLogger;
68+
export declare let commonLogger: PancloudLogger;
6869
/**
6970
* Developer might decide to change the loglevel of the logger object at runtime
7071
* @param newLevel the new log level
7172
*/
72-
export declare function setLogLevel(newLevel: logLevel): void;
73+
export declare function setLogLevel(newLevel: LogLevel): void;
7374
/**
7475
* Changes the common logger variable to a user-provided object
7576
* @param logger user provided pancloudLogger compliant object to be used for SDK logging
7677
*/
77-
export declare function setLogger(logger: pancloudLogger): void;
78+
export declare function setLogger(logger: PancloudLogger): void;
7879
/**
7980
* Abstract function used to retry multiple times a user-provided operation
8081
* @param source class using the retrier. Its className property value will be used in logs generated by the retrier
@@ -83,5 +84,7 @@ export declare function setLogger(logger: pancloudLogger): void;
8384
* @param handler function that implements the operation
8485
* @param params additional arguments to be passed to the handler function
8586
*/
86-
export declare function retrier<T, O>(source: pancloudClass, n: number | undefined, delay: number | undefined, handler: (...args: T[]) => Promise<O>, ...params: T[]): Promise<O>;
87+
export declare function retrier<T, O>(source: PancloudClass, n: number | undefined, delay: number | undefined, handler: (...args: T[]) => Promise<O>, ...params: T[]): Promise<O>;
88+
export declare function expTokenExtractor(source: PancloudClass, token: string): number;
89+
export declare function uid(): string;
8790
export {};

dist/common.js

Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
11
"use strict";
2+
// Copyright 2015-2019 Palo Alto Networks, Inc
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
Object.defineProperty(exports, "__esModule", { value: true });
215
/**
316
* Provides common resources for other modules in the pancloud SDK
417
*/
5-
Object.defineProperty(exports, "__esModule", { value: true });
6-
var logLevel;
7-
(function (logLevel) {
8-
logLevel[logLevel["DEBUG"] = 0] = "DEBUG";
9-
logLevel[logLevel["INFO"] = 1] = "INFO";
10-
logLevel[logLevel["ALERT"] = 2] = "ALERT";
11-
logLevel[logLevel["ERROR"] = 3] = "ERROR";
12-
})(logLevel = exports.logLevel || (exports.logLevel = {}));
18+
const error_1 = require("./error");
19+
const crypto_1 = require("crypto");
20+
var LogLevel;
21+
(function (LogLevel) {
22+
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
23+
LogLevel[LogLevel["INFO"] = 1] = "INFO";
24+
LogLevel[LogLevel["ALERT"] = 2] = "ALERT";
25+
LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
26+
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
1327
const LTYPES = {
1428
"panw.auth": "",
1529
"panw.config": "",
@@ -34,14 +48,18 @@ const LTYPES = {
3448
"tms.threat": "",
3549
"tms.traps": ""
3650
};
51+
exports.region2EntryPoint = {
52+
'americas': 'https://api.us.paloaltonetworks.com',
53+
'europe': 'https://api.eu.paloaltonetworks.com'
54+
};
3755
function isKnownLogType(t) {
3856
return LTYPES.hasOwnProperty(t);
3957
}
4058
exports.isKnownLogType = isKnownLogType;
4159
/**
4260
* Centralized logging capability for the whole pancloud SDK
4361
*/
44-
class sdkLogger {
62+
class SdkLogger {
4563
/**
4664
*
4765
* @param level only messages with a level equal or avobe this provided value will be loogged
@@ -52,16 +70,16 @@ class sdkLogger {
5270
this.stackTrace = stackTrace;
5371
}
5472
error(e) {
55-
this.format(e.getSourceClass(), e.getErrorMessage(), logLevel.ERROR, e.name, e.getErrorCode(), undefined, e.stack);
73+
this.format(e.getSourceClass(), e.getErrorMessage(), LogLevel.ERROR, e.name, e.getErrorCode(), undefined, e.stack);
5674
}
5775
alert(source, message, name) {
58-
this.format(source.className, message, logLevel.ALERT, name);
76+
this.format(source.className, message, LogLevel.ALERT, name);
5977
}
6078
info(source, message, name) {
61-
this.format(source.className, message, logLevel.INFO, name);
79+
this.format(source.className, message, LogLevel.INFO, name);
6280
}
6381
debug(source, message, name, payload) {
64-
this.format(source.className, message, logLevel.DEBUG, name, undefined, payload);
82+
this.format(source.className, message, LogLevel.DEBUG, name, undefined, payload);
6583
}
6684
format(source, message, level, name, code, payload, stack) {
6785
if (level >= this.level) {
@@ -98,12 +116,12 @@ class sdkLogger {
98116
finalOutput += ` payload=${payloadOut}`;
99117
}
100118
switch (level) {
101-
case logLevel.ERROR: {
119+
case LogLevel.ERROR: {
102120
console.error(finalOutput);
103121
break;
104122
}
105-
case logLevel.ALERT:
106-
case logLevel.INFO: {
123+
case LogLevel.ALERT:
124+
case LogLevel.INFO: {
107125
console.info(finalOutput);
108126
break;
109127
}
@@ -120,7 +138,7 @@ class sdkLogger {
120138
/**
121139
* Instantiate a module-provided logger at load time
122140
*/
123-
exports.commonLogger = new sdkLogger(logLevel.INFO, false);
141+
exports.commonLogger = new SdkLogger(LogLevel.INFO, false);
124142
/**
125143
* Developer might decide to change the loglevel of the logger object at runtime
126144
* @param newLevel the new log level
@@ -164,3 +182,26 @@ async function retrier(source, n = 3, delay = 100, handler, ...params) {
164182
throw (lastError) ? lastError : new Error('reties exhausted');
165183
}
166184
exports.retrier = retrier;
185+
function expTokenExtractor(source, token) {
186+
let parts = token.split('.');
187+
if (parts.length != 3) {
188+
throw new error_1.PanCloudError(source, 'PARSER', 'Not a valid JWT token format');
189+
}
190+
let expAttribute;
191+
try {
192+
expAttribute = JSON.parse(Buffer.from(parts[1], 'base64').toString()).exp;
193+
}
194+
catch (_a) {
195+
throw new error_1.PanCloudError(source, 'PARSER', 'Not a valid JWT token format');
196+
}
197+
if (typeof expAttribute == 'number') {
198+
return expAttribute;
199+
}
200+
throw new error_1.PanCloudError(source, 'PARSER', 'JWT token does not have a valid "exp" field');
201+
}
202+
exports.expTokenExtractor = expTokenExtractor;
203+
function uid() {
204+
let data = `pancloud${Date.now()}nodejs`;
205+
return crypto_1.createHash('sha1').update(data).digest('base64');
206+
}
207+
exports.uid = uid;

dist/core.d.ts

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
1+
/**
2+
* Implements the abstract coreClass that implements common methods for higher-end classes like Event Service
3+
* and Logging Service
4+
*/
5+
import { HttpMethod } from './fetch';
16
import { Credentials } from './credentials';
2-
import { logLevel } from './common';
3-
export interface coreStats {
7+
import { LogLevel } from './common';
8+
/**
9+
* Core class runtime statistic metrics
10+
*/
11+
export interface CoreStats {
12+
/**
13+
* The number of API transactions completed
14+
*/
415
apiTransactions: number;
516
}
617
/**
718
* Interface to provide configuration options to the core class
819
*/
9-
export interface coreOptions {
10-
/**
11-
* credential object that should be used in the coreClass instance
12-
*/
13-
credential: Credentials;
14-
/**
15-
* Toggle the access_token auto-refresh feature
16-
*/
17-
autoRefresh?: boolean;
20+
export interface CoreOptions {
1821
/**
1922
* Minimum level of logs that should be generated by the coreClass
2023
*/
21-
level?: logLevel;
24+
level?: LogLevel;
2225
/**
2326
* Number of times a fetch operation must be retried in case of exception
2427
*/
@@ -27,13 +30,16 @@ export interface coreOptions {
2730
* Delay (in milliseconds) between retry attempts
2831
*/
2932
retrierDelay?: number;
33+
/**
34+
* If provided, the underlying `fetch` module will use this value as request timeout
35+
*/
3036
fetchTimeout?: number | undefined;
3137
}
3238
/**
3339
* This class should not be used directly. It is meant to be extended. Use higher-level classes like LoggingService
3440
* or EventService
3541
*/
36-
export declare class coreClass {
42+
export declare class CoreClass {
3743
/**
3844
* Credential object to be used by this instance
3945
*/
@@ -49,17 +55,17 @@ export declare class coreClass {
4955
[i: string]: string;
5056
};
5157
private fetchTimeout;
52-
private autoR;
5358
private retrierCount?;
5459
private retrierDelay?;
5560
lastResponse: any;
5661
className: string;
57-
protected stats: coreStats;
62+
protected stats: CoreStats;
5863
/**
5964
*
65+
* @param cred credentials object instance that will provide the needed JWT access_token
6066
* @param ops configuration options for this instance
6167
*/
62-
protected constructor(baseUrl: string, ops: coreOptions);
68+
protected constructor(cred: Credentials, basePath: string, ops?: CoreOptions);
6369
/**
6470
* Prepares the HTTP headers. Mainly used to keep the Autorization header (bearer access-token)
6571
*/
@@ -95,5 +101,5 @@ export declare class coreClass {
95101
/**
96102
* Convenience method that abstracts a DELETE operation to the Application Framework
97103
*/
98-
protected void_X_Operation(path?: string, payload?: string, method?: string): Promise<void>;
104+
protected voidXOperation(path?: string, payload?: string, method?: HttpMethod): Promise<void>;
99105
}

0 commit comments

Comments
 (0)