@adobe/acc-js-sdk 1.0.5 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adobe/acc-js-sdk",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "ACC Javascript SDK",
5
5
  "main": "src/index.js",
6
6
  "homepage": "https://github.com/adobe/acc-js-sdk#readme",
@@ -16,7 +16,7 @@
16
16
  "devDependencies": {
17
17
  "docdash": "^1.2.0",
18
18
  "eslint": "^7.32.0",
19
- "jest": "^27.2.0",
19
+ "jest": "^27.2.5",
20
20
  "jest-junit": "^13.0.0",
21
21
  "jsdoc": "^3.6.7",
22
22
  "jsdoc-to-markdown": "^7.0.1",
package/src/cache.js ADDED
@@ -0,0 +1,275 @@
1
+ /*
2
+ Copyright 2020 Adobe. All rights reserved.
3
+ This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License. You may obtain a copy
5
+ of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ Unless required by applicable law or agreed to in writing, software distributed under
8
+ the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ OF ANY KIND, either express or implied. See the License for the specific language
10
+ governing permissions and limitations under the License.
11
+ */
12
+ (function() {
13
+ "use strict";
14
+
15
+
16
+ /**********************************************************************************
17
+ *
18
+ * Cache utilities
19
+ *
20
+ *********************************************************************************/
21
+
22
+ /**
23
+ * @namespace Utils
24
+ */
25
+
26
+
27
+ /**********************************************************************************
28
+ *
29
+ * A simple cache for XtkEntities, options, etc.
30
+ *
31
+ *********************************************************************************/
32
+
33
+ /**
34
+ * @private
35
+ * @class
36
+ * @constructor
37
+ * @memberof Utils
38
+ */
39
+ class SafeStorage {
40
+
41
+ /**
42
+ * A wrapper to the Storage interface (LocalStorage, etc.) which is "safe", i.e.
43
+ *
44
+ * - it will never throw / support local stroage to be undefined or not accessible
45
+ * - Handle the notion of "root key", i.e. prefix
46
+ * - Set/get values as JSON only and not as strings
47
+ * - Silently caches all exceptions
48
+ * - Automatically remove from storage cached values which are not valid, expired, or cannot be parsed
49
+ *
50
+ * SafeStorage objects are created automatically by Caches
51
+ *
52
+ * @param {Storage} delegate an optional delegate options, confomring to the Storage interface (getItem, setItem, removeItem)
53
+ * @param {string} rootKey an optional prefix which will be prepend to all keys
54
+ * @param {function} serDeser serializarion & deserialization function. First parameter is the object or value to serialize
55
+ * or deserialize, and second parameter is true for serialization or false for deserialization
56
+ */
57
+ constructor(delegate, rootKey, serDeser) {
58
+ if (!serDeser)
59
+ serDeser = (item, serDeser) => {
60
+ if (serDeser) {
61
+ if (!item) throw Error(`Cannot serialize falsy cached item`);
62
+ if (typeof item !== "object") throw Error(`Cannot serialize non-object`);
63
+ return JSON.stringify(item);
64
+ }
65
+ else {
66
+ if (!item) throw Error(`Cannot deserialize falsy cached item`);
67
+ return JSON.parse(item);
68
+ }
69
+ };
70
+ this._delegate = delegate;
71
+ this._rootKey = rootKey ? `${rootKey}$` : "";
72
+ this._serDeser = serDeser;
73
+ }
74
+
75
+ /**
76
+ * Get an item from storage
77
+ * @param {string} key the item key (relative to the root key)
78
+ * @returns {Utils.CachedObject} the cached object, or undefined if not found.
79
+ * The storage serDeser fucntion will be used to deserialize the cached value
80
+ */
81
+ getItem(key) {
82
+ if (!this._delegate || this._rootKey === undefined || this._rootKey === null)
83
+ return;
84
+ const itemKey = `${this._rootKey}${key}`;
85
+ const raw = this._delegate.getItem(itemKey);
86
+ if (!raw)
87
+ return undefined;
88
+ try {
89
+ return this._serDeser(raw, false);
90
+ } catch(ex) {
91
+ this.removeItem(key);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Put an item into storage
97
+ * @param {string} key the item key (relative to the root key)
98
+ * @param {Utils.CachedObject} json the object to cache
99
+ * The storage serDeser fucntion will be used to serialize the cached value
100
+ */
101
+ setItem(key, json) {
102
+ if (!this._delegate || this._rootKey === undefined || this._rootKey === null)
103
+ return;
104
+ try {
105
+ //if (json && typeof json === "object") {
106
+ const raw = this._serDeser(json, true);
107
+ this._delegate.setItem(`${this._rootKey}${key}`, raw);
108
+ return;
109
+ } catch(ex) { /* Ignore errors in safe class */
110
+ }
111
+ this.removeItem(key);
112
+ }
113
+
114
+ /**
115
+ * Removes an item from the storage
116
+ * @param {string} key the item key (relative to the root key)
117
+ */
118
+ removeItem(key) {
119
+ if (!this._delegate || this._rootKey === undefined || this._rootKey === null)
120
+ return;
121
+ try {
122
+ this._delegate.removeItem(`${this._rootKey}${key}`);
123
+ } catch(ex) { /* Ignore errors in safe class */
124
+ }
125
+ }
126
+ }
127
+
128
+ /**
129
+ * @private
130
+ * @class
131
+ * @constructor
132
+ * @memberof Utils
133
+ */
134
+ class CachedObject {
135
+
136
+ /**
137
+ * An object in the cache, i.e. a wrapped to a cached value and additional metadata to manage the cache.
138
+ * Do not create such objects directly, they are 100% managed by the Cache object
139
+ *
140
+ * @param {*} value the cached value
141
+ * @param {number} cachedAt the timestamp at which the value was cached
142
+ * @param {number} expiresAt the timestamp at which the cached value expires
143
+ */
144
+ constructor(value, cachedAt, expiresAt) {
145
+ this.value = value;
146
+ this.cachedAt = cachedAt;
147
+ this.expiresAt = expiresAt;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * @private
153
+ * @class
154
+ * @constructor
155
+ * @memberof Utils
156
+ */
157
+ class Cache {
158
+
159
+ /**
160
+ * A general purpose in-memory cache with TTL. In addition to caching in memory, the cache has the ability to delegate the caching
161
+ * to a persistent cache, such as the browser localStorage. The interface is 100% synchronous.
162
+ *
163
+ * By default, caches take a single parameter for the key. It is possible however to use a more complex scenario by setting a makeKeyFn.
164
+ * When set, such a function will take 1 or more arguments and will be responsible to create a primitive key (a string) from the arguments.
165
+ * The cache public APIs : get and put therefore can take a variable number of key arguments, which will be combined into the actual primitive key.
166
+ *
167
+ * @param {Storage} storage is an optional Storage object, such as localStorage or sessionStorage. This object will be wrapped into a SafeStorage object to ensure access is safe and will not throw any exceptions
168
+ * @param {string} rootKey is an optional root key to use for the storage object
169
+ * @param {number} ttl is the TTL for objects in ms. Defaults to 5 mins
170
+ * @param {function} makeKeyFn is an optional function which will generate a key for objects in the cache. It's passed the arguments of the cache 'get' function
171
+ * @param {function} serDeser serializarion & deserialization function. First parameter is the object or value to serialize
172
+ * or deserialize, and second parameter is true for serialization or false for deserialization
173
+ */
174
+ constructor(storage, rootKey, ttl, makeKeyFn, serDeser) {
175
+ this._storage = new SafeStorage(storage, rootKey, serDeser);
176
+ this._ttl = ttl || 1000*300;
177
+ this._makeKeyFn = makeKeyFn || ((x) => x);
178
+ this._cache = {};
179
+ // timestamp at which the cache was last cleared
180
+ this._lastCleared = this._loadLastCleared();
181
+ }
182
+
183
+ // Load timestamp at which the cache was last cleared
184
+ _loadLastCleared() {
185
+ const json = this._storage.getItem("lastCleared");
186
+ return json ? json.timestamp : undefined;
187
+ }
188
+
189
+ _saveLastCleared() {
190
+ const now = Date.now();
191
+ this._lastCleared = now;
192
+ this._storage.setItem("lastCleared", { timestamp: now});
193
+ }
194
+
195
+ // Load from local storage
196
+ _load(key) {
197
+ const json = this._storage.getItem(key);
198
+ if (!json || !json.cachedAt || json.cachedAt <= this._lastCleared) {
199
+ this._storage.removeItem(key);
200
+ return;
201
+ }
202
+ return json;
203
+ }
204
+
205
+ // Save to local storage
206
+ _save(key, cached) {
207
+ this._storage.setItem(key, cached);
208
+ }
209
+
210
+ // Remove from local storage
211
+ _remove(key) {
212
+ this._storage.removeItem(key);
213
+ }
214
+
215
+ _getIfActive(key) {
216
+ // In memory cache?
217
+ var cached = this._cache[key];
218
+ // Local storage ?
219
+ if (!cached) {
220
+ cached = this._load(key);
221
+ this._cache[key] = cached;
222
+ }
223
+ if (!cached)
224
+ return undefined;
225
+ if (cached.expiresAt <= Date.now()) {
226
+ delete this._cache[key];
227
+ this._remove(key);
228
+ return undefined;
229
+ }
230
+ return cached.value;
231
+ }
232
+
233
+ /**
234
+ * Get a value from the cache
235
+ * @param {*} key the key or keys of the value to retreive
236
+ * @returns {*} the cached value, or undefined if not found
237
+ */
238
+ get() {
239
+ const key = this._makeKeyFn.apply(this, arguments);
240
+ const cached = this._getIfActive(key);
241
+ return cached;
242
+ }
243
+
244
+ /**
245
+ * Put a value from the cache
246
+ * @param {*} key the key or keys of the value to retreive
247
+ * @param {*} value the value to cache
248
+ * @returns {CachedObject} a cached object containing the cached value
249
+ */
250
+ put() {
251
+ const value = arguments[arguments.length -1];
252
+ const key = this._makeKeyFn.apply(this, arguments);
253
+ const now = Date.now();
254
+ const expiresAt = now + this._ttl;
255
+ const cached = new CachedObject(value, now, expiresAt);
256
+ this._cache[key] = cached;
257
+ this._save(key, cached);
258
+ return cached;
259
+ }
260
+
261
+ /**
262
+ * Removes everything from the cache. It does not directly removes data from persistent storage if there is, but it marks the cache
263
+ * as cleared so that subsequent get operation will not actually return any data cached in persistent storage
264
+ */
265
+ clear() {
266
+ this._cache = {};
267
+ this._saveLastCleared();
268
+ }
269
+ }
270
+
271
+ // Public expots
272
+ exports.SafeStorage = SafeStorage;
273
+ exports.Cache = Cache;
274
+
275
+ })();
package/src/client.js CHANGED
@@ -178,11 +178,15 @@ class Credentials {
178
178
  */
179
179
  constructor(type, sessionToken, securityToken) {
180
180
  if (type != "UserPassword" && type != "ImsServiceToken" && type != "SessionToken" &&
181
- type != "AnonymousUser" && type != "SecurityToken")
181
+ type != "AnonymousUser" && type != "SecurityToken" && type != "BearerToken")
182
182
  throw CampaignException.INVALID_CREDENTIALS_TYPE(type);
183
183
  this._type = type;
184
184
  this._sessionToken = sessionToken || "";
185
185
  this._securityToken = securityToken || "";
186
+ if (type == "BearerToken") {
187
+ this._bearerToken = sessionToken || "";
188
+ this._sessionToken = "";
189
+ }
186
190
  }
187
191
 
188
192
  /**
@@ -308,6 +312,18 @@ class ConnectionParameters {
308
312
  return new ConnectionParameters(endpoint, credentials, options);
309
313
  }
310
314
 
315
+ /**
316
+ * Creates connection parameters for a Campaign instance from bearer token
317
+ *
318
+ * @param {string} endpoint The campaign endpoint (URL)
319
+ * @param {string} bearerToken IMS bearer token
320
+ * @param {*} options connection options
321
+ * @returns {ConnectionParameters} a ConnectionParameters object which can be used to create a Client
322
+ */
323
+ static ofBearerToken(endpoint, bearerToken, options) {
324
+ const credentials = new Credentials("BearerToken", bearerToken);
325
+ return new ConnectionParameters(endpoint, credentials, options);
326
+ }
311
327
  /**
312
328
  * Creates connection parameters for a Campaign instance, using an IMS service token and a user name (the user to impersonate)
313
329
  *
@@ -624,6 +640,17 @@ class Client {
624
640
  if (credentialsType == "AnonymousUser")
625
641
  return true;
626
642
 
643
+ // When using bearer token authentication we are considered logged only after
644
+ // the bearer token has been converted into session token and security token
645
+ // by method xtk:session#BearerTokenLogon
646
+ if( credentialsType == "BearerToken")
647
+ return this._sessionToken != undefined &&
648
+ this._sessionToken != null &&
649
+ this._sessionToken != "" &&
650
+ this._securityToken != undefined &&
651
+ this._securityToken != null &&
652
+ this._securityToken != "";
653
+
627
654
  // with session token authentication, we do not expect a security token
628
655
  // with security token authentication, we do not expect a session token
629
656
  const needsSecurityToken = credentialsType != "SessionToken";
@@ -708,28 +735,32 @@ class Client {
708
735
  that.application = new Application(that);
709
736
  return Promise.resolve();
710
737
  }
711
- else if (credentials._type == "SecurityToken") {
712
- that._sessionInfo = undefined;
738
+ else if (credentials._type == "SecurityToken") {
739
+ that._sessionInfo = undefined;
713
740
  that._installedPackages = {};
714
741
  that._sessionToken = "";
715
742
  that._securityToken = credentials._securityToken;
716
743
  that.application = new Application(that);
717
744
  return Promise.resolve();
718
745
  }
719
- else if (credentials._type == "UserPassword") {
720
- const user = credentials._getUser();
721
- const password = credentials._getPassword();
722
-
723
- const soapCall = this._prepareSoapCall("xtk:session", "Logon");
724
- soapCall.writeString("login", user);
725
- soapCall.writeString("password", password);
726
- var parameters = null;
727
- if (this._connectionParameters._options.rememberMe) {
728
- parameters = soapCall.createElement("parameters");
729
- parameters.setAttribute("rememberMe", "true");
746
+ else if (credentials._type == "UserPassword" || credentials._type == "BearerToken") {
747
+ const soapCall = that._prepareSoapCall("xtk:session", credentials._type === "UserPassword" ? "Logon" : "BearerTokenLogon");
748
+ if (credentials._type == "UserPassword") {
749
+ const user = credentials._getUser();
750
+ const password = credentials._getPassword();
751
+ soapCall.writeString("login", user);
752
+ soapCall.writeString("password", password);
753
+ var parameters = null;
754
+ if (this._connectionParameters._options.rememberMe) {
755
+ parameters = soapCall.createElement("parameters");
756
+ parameters.setAttribute("rememberMe", "true");
757
+ }
758
+ soapCall.writeElement("parameters", parameters);
730
759
  }
731
- soapCall.writeElement("parameters", parameters);
732
-
760
+ else {
761
+ const bearerToken = credentials._bearerToken;
762
+ soapCall.writeString("bearerToken", bearerToken);
763
+ }
733
764
  return this._makeSoapCall(soapCall).then(function() {
734
765
  const sessionToken = soapCall.getNextString();
735
766
 
@@ -20,7 +20,7 @@ governing permissions and limitations under the License.
20
20
  *********************************************************************************/
21
21
 
22
22
  const DomUtil = require('./domUtil.js').DomUtil;
23
- const { Cache } = require('./util.js');
23
+ const { Cache } = require('./cache.js');
24
24
 
25
25
  /**
26
26
  * @namespace Campaign
@@ -41,12 +41,31 @@ class MethodCache extends Cache {
41
41
  * A in-memory cache for SOAP call method definitions. Not intended to be used directly,
42
42
  * but an internal cache for the Campaign.Client object
43
43
  *
44
+ * Cached object are made of
45
+ * - the key is a string in the form <schemaId>#<methodName>, such as "xtk:session#GetServerTime"
46
+ * - the value is a JSON object made of two attributes:
47
+ * - the "urn" attribute, such as "xtk:persist", which is the URN to use to make the SOAP call
48
+ * - the "method" attribute, a DOM element corresponding to the method XML element
49
+ *
44
50
  * @param {Storage} storage is an optional Storage object, such as localStorage or sessionStorage
45
51
  * @param {string} rootKey is an optional root key to use for the storage object
46
52
  * @param {number} ttl is the TTL for objects in ms. Defaults to 5 mins
47
53
  */
48
54
  constructor(storage, rootKey, ttl) {
49
- super(storage, rootKey, ttl, ((schemaId, methodName) => schemaId + "#" + methodName ));
55
+ super(storage, rootKey, ttl, ((schemaId, methodName) => schemaId + "#" + methodName ), (item, serDeser) => {
56
+ if (serDeser) {
57
+ if (!item || !item.value || !item.value.method) throw Error(`Cannot serialize falsy cached item`);
58
+ const value = Object.assign({}, item); // shallow copy
59
+ value.value = Object.assign({}, value.value); // dummy deep copy
60
+ value.value.method = DomUtil.toXMLString(item.value.method);
61
+ return JSON.stringify(value);
62
+ }
63
+ else {
64
+ const json = JSON.parse(item);
65
+ json.value.method = DomUtil.parse(json.value.method).documentElement;
66
+ return json;
67
+ }
68
+ });
50
69
  }
51
70
 
52
71
  /**
@@ -18,7 +18,7 @@ governing permissions and limitations under the License.
18
18
  *
19
19
  *********************************************************************************/
20
20
  const XtkCaster = require('./xtkCaster.js').XtkCaster;
21
- const { Cache } = require('./util.js');
21
+ const { Cache } = require('./cache.js');
22
22
 
23
23
 
24
24
  /**
@@ -44,6 +44,10 @@ class OptionCache extends Cache {
44
44
  * A in-memory cache for xtk option values. Not intended to be used directly,
45
45
  * but an internal cache for the Campaign.Client object
46
46
  *
47
+ * Cached object are made of
48
+ * - the key is the option name
49
+ * - the value is the option, a JSON object made of value, type, and rawValue properties
50
+ *
47
51
  * @param {Storage} storage is an optional Storage object, such as localStorage or sessionStorage
48
52
  * @param {string} rootKey is an optional root key to use for the storage object
49
53
  * @param {number} ttl is the TTL for objects in ms. Defaults to 5 mins
package/src/soap.js CHANGED
@@ -119,7 +119,8 @@ class SoapMethodCall {
119
119
  * @returns {boolean} indicates if the call requires a Logon first
120
120
  */
121
121
  requiresLogon() {
122
- const requiresLogon = !(this.urn === "xtk:session" && this.methodName === "Logon");
122
+ const requiresLogon = !(this.urn === "xtk:session" &&
123
+ (this.methodName === "Logon" || this.methodName === "BearerTokenLogon") ) ;
123
124
  return requiresLogon;
124
125
  }
125
126