@contrail/flexplm 1.7.6 → 1.7.7-alpha.01fb300

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.
@@ -5,10 +5,19 @@ export declare class FlexPLMConnect {
5
5
  private staticHeaders;
6
6
  payloadSendAsArray: boolean;
7
7
  constructor(_config: FCConfig, endPoint?: any, payloadAsArray?: any);
8
+ private get sessionOptions();
9
+ private getSessionKey;
10
+ private getCachedSession;
11
+ private storeSession;
12
+ private clearSession;
13
+ /** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
14
+ private extractSessionCookie;
15
+ private cookieHeader;
8
16
  private getRequestOptions;
9
- getCSRF(): Promise<{
17
+ getCSRF(getNewSession?: boolean): Promise<{
10
18
  nonce_key: any;
11
19
  nonce: any;
20
+ sessionCookie: string;
12
21
  }>;
13
22
  sendRequest(csrf: any, payload: any): Promise<Response>;
14
23
  protected processRequest(payload: any): Promise<FlexPLMResponseData>;
@@ -2,6 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FlexPLMConnect = void 0;
4
4
  const app_framework_1 = require("@contrail/app-framework");
5
+ // Module-level on purpose: a new FlexPLMConnect is constructed for every event. Declaring for Session reusing use case.
6
+ const sessionCache = new Map();
7
+ // Added for Session reuse - ET-390 - Ends
5
8
  class FlexPLMConnect {
6
9
  constructor(_config, endPoint = undefined, payloadAsArray = undefined) {
7
10
  this.vibeEventEndpoint = '';
@@ -19,9 +22,90 @@ class FlexPLMConnect {
19
22
  }
20
23
  }
21
24
  /////////////////////////////////////////////////////////////////////////////
25
+ ///////// ET-390 - Session reuse: start
26
+ /////////////////////////////////////////////////////////////////////////////
27
+ /*
28
+ private get sessionOptions() {
29
+ const sessReuseBool = this.config?.flexplmConnect?.sessionReuse;
30
+ console.info('sessReuseBool value is --> ' + sessReuseBool);
31
+ console.info('enabled value is --> ' + sessReuseBool?.enabled);
32
+ return {
33
+ enabled: sessReuseBool?.enabled === true || String(sessReuseBool?.enabled).toLowerCase() === 'true',
34
+ ttlMs: (sessReuseBool?.ttlSeconds ?? 900) * 1000,
35
+ cookieName: sessReuseBool?.cookieName ?? 'JSESSIONID',
36
+ retryStatuses: (sessReuseBool?.retryStatuses ?? [401, 403]) as number[],
37
+ };
38
+ }
39
+ */
40
+ get sessionOptions() {
41
+ const cfg = this.config ?? {};
42
+ const sessReuseEntries = (name) => cfg[`flexplmConnect.sessionReuse.${name}`];
43
+ const enabled = sessReuseEntries('enabled');
44
+ return {
45
+ enabled: enabled === true || String(enabled).toLowerCase() === 'true',
46
+ ttlMs: (sessReuseEntries('ttlSeconds') ?? 900) * 1000,
47
+ cookieName: sessReuseEntries('cookieName') ?? 'JSESSIONID',
48
+ retryStatuses: (sessReuseEntries('retryStatuses') ?? [401, 403]),
49
+ };
50
+ }
51
+ getSessionKey() {
52
+ return [this.config.apiHost, this.config.urlContext, this.config.userName(), this.config.plmEnviornment].join('|');
53
+ }
54
+ getCachedSession() {
55
+ if (!this.sessionOptions.enabled)
56
+ return undefined;
57
+ const key = this.getSessionKey();
58
+ const cachedSessValue = sessionCache.get(key);
59
+ if (!cachedSessValue)
60
+ return undefined;
61
+ if (cachedSessValue.expiresAt <= Date.now()) {
62
+ sessionCache.delete(key);
63
+ return undefined;
64
+ }
65
+ return cachedSessValue.cookie;
66
+ }
67
+ storeSession(cookie) {
68
+ // sliding expiry: Windchill's session timeout is also sliding
69
+ sessionCache.set(this.getSessionKey(), { cookie, expiresAt: Date.now() + this.sessionOptions.ttlMs });
70
+ }
71
+ clearSession() {
72
+ sessionCache.delete(this.getSessionKey());
73
+ }
74
+ /** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
75
+ extractSessionCookie(response) {
76
+ const respHeader = response?.headers;
77
+ if (!respHeader)
78
+ return undefined;
79
+ let raw = [];
80
+ if (typeof respHeader.getSetCookie === 'function') {
81
+ raw = respHeader.getSetCookie();
82
+ }
83
+ else if (typeof respHeader.get === 'function' && respHeader.get('set-cookie')) {
84
+ raw = [respHeader.get('set-cookie')];
85
+ }
86
+ const name = this.sessionOptions.cookieName;
87
+ const regexFilter = new RegExp('(?:^|[,\\s])' + name + '=([^;,\\s]+)', 'g');
88
+ let jSession;
89
+ for (const line of raw) {
90
+ let cookieNameMatcher = regexFilter.exec(line);
91
+ while (cookieNameMatcher !== null) {
92
+ jSession = cookieNameMatcher[1];
93
+ cookieNameMatcher = regexFilter.exec(line);
94
+ }
95
+ }
96
+ return jSession;
97
+ }
98
+ cookieHeader(sessionCookie) {
99
+ return sessionCookie ? `${this.sessionOptions.cookieName}=${sessionCookie}` : undefined;
100
+ }
101
+ /////////////////////////////////////////////////////////////////////////////
102
+ ///////// ET-390 - Session reuse: end
103
+ /////////////////////////////////////////////////////////////////////////////
104
+ /////////////////////////////////////////////////////////////////////////////
22
105
  ///////// Custom getRequestOptions: start
23
106
  /////////////////////////////////////////////////////////////////////////////
24
- getRequestOptions(method) {
107
+ // ET-390 - adding a new parameter sessionCookie to the getRequestOptions function
108
+ getRequestOptions(method, sessionCookie) {
25
109
  const csrfOptions = {
26
110
  method,
27
111
  headers: {
@@ -33,9 +117,19 @@ class FlexPLMConnect {
33
117
  if (this.staticHeaders) {
34
118
  Object.assign(csrfOptions.headers, this.staticHeaders);
35
119
  }
120
+ // Added for Session reuse - ET-390 - Starts
121
+ const cookie = this.cookieHeader(sessionCookie);
122
+ if (cookie) {
123
+ csrfOptions.headers['Cookie'] = cookie;
124
+ }
125
+ // Added for Session reuse - ET-390 - Ends
36
126
  if (app_framework_1.Logger.isInfoOn()) {
37
127
  const logOptions = JSON.parse(JSON.stringify(csrfOptions));
38
128
  logOptions['headers']['Authorization'] = logOptions?.headers?.Authorization.substring(0, 9);
129
+ // Added for Session reuse - ET-390 - Starts
130
+ if (logOptions.headers['Cookie'])
131
+ logOptions.headers['Cookie'] = '***masked***';
132
+ // Added for Session reuse - ET-390 - Ends
39
133
  console.info('csrfOptions: ' + JSON.stringify(logOptions));
40
134
  }
41
135
  return csrfOptions;
@@ -43,13 +137,30 @@ class FlexPLMConnect {
43
137
  /////////////////////////////////////////////////////////////////////////////
44
138
  ///////// Custom getRequestOptions: end
45
139
  /////////////////////////////////////////////////////////////////////////////
46
- async getCSRF() {
140
+ // ET-390 - adding a new parameter getNewSession to the getCSRF function
141
+ // Whenever a getCSRF is called without getNewSession, the default value of false will be used
142
+ async getCSRF(getNewSession = false) {
47
143
  const urlContext = this.config.urlContext;
48
144
  const csrfEndpoint = this.config.csrfEndpoint;
49
145
  const csrfURL = this.config.apiHost + urlContext + csrfEndpoint;
50
146
  console.info('csrfURL: ' + csrfURL);
51
- const csrfOptions = this.getRequestOptions('GET');
52
- const response = await fetch(csrfURL, csrfOptions);
147
+ // Added for Session reuse - ET-390 - Starts
148
+ if (getNewSession)
149
+ this.clearSession();
150
+ let sentCookie = this.getCachedSession();
151
+ // getRequestOptions will be called with additional sentCookie parameter
152
+ const csrfOptions = this.getRequestOptions('GET', sentCookie);
153
+ // Added for Session reuse - ET-390 - Ends
154
+ let response = await fetch(csrfURL, csrfOptions);
155
+ // Added for Session reuse - ET-390 - Starts
156
+ // if the response status is 401 or 403, then get a new session id
157
+ if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
158
+ console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
159
+ this.clearSession();
160
+ sentCookie = undefined;
161
+ response = await fetch(csrfURL, this.getRequestOptions('GET'));
162
+ }
163
+ // Added for Session reuse - ET-390 - Ends
53
164
  if (response.status >= 300) {
54
165
  const message = 'Error connecting to FlexPLM:status: ' + response.status;
55
166
  console.error(message);
@@ -58,14 +169,24 @@ class FlexPLMConnect {
58
169
  e['httpResponseStatus'] = response.status;
59
170
  throw e;
60
171
  }
172
+ // Added for Session reuse - ET-390 - Starts
173
+ // If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
174
+ let sessionCookie = sentCookie;
175
+ if (this.sessionOptions.enabled) {
176
+ sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
177
+ if (sessionCookie)
178
+ this.storeSession(sessionCookie);
179
+ }
180
+ // Added for Session reuse - ET-390 - Ends
61
181
  try {
62
182
  const body = await response.json();
63
183
  const nonce_key = body.items[0].attributes.nonce_key;
64
184
  const nonce = body.items[0].attributes.nonce;
65
- console.info('nonce_key: ' + nonce_key);
185
+ // ET-390 - adding sessionCookie to the return
66
186
  return {
67
187
  nonce_key,
68
- nonce
188
+ nonce,
189
+ sessionCookie,
69
190
  };
70
191
  }
71
192
  catch (e) {
@@ -79,7 +200,7 @@ class FlexPLMConnect {
79
200
  if (this.payloadSendAsArray && !Array.isArray(payload)) {
80
201
  payload = [payload];
81
202
  }
82
- const xferOptions = this.getRequestOptions('POST');
203
+ const xferOptions = this.getRequestOptions('POST', csrf?.sessionCookie);
83
204
  xferOptions['body'] = JSON.stringify(payload);
84
205
  xferOptions.headers[csrf.nonce_key] = csrf.nonce;
85
206
  const urlContext = this.config.urlContext;
@@ -90,6 +211,8 @@ class FlexPLMConnect {
90
211
  const logOptions = JSON.parse(JSON.stringify(xferOptions));
91
212
  if (logOptions?.headers?.Authorization)
92
213
  logOptions.headers.Authorization = logOptions?.headers?.Authorization.substring(0, 9);
214
+ if (logOptions?.headers?.Cookie)
215
+ logOptions.headers.Cookie = '***masked***';
93
216
  if (csrf?.nonce_key)
94
217
  logOptions.headers[csrf.nonce_key] = csrf.nonce ? `***masked(length:${csrf.nonce.length})***` : '***masked(empty)***';
95
218
  console.info('csrfOptions: ' + JSON.stringify(logOptions));
@@ -107,13 +230,21 @@ class FlexPLMConnect {
107
230
  if (app_framework_1.Logger.isInfoOn()) {
108
231
  console.info('payload: ' + JSON.stringify(payload));
109
232
  }
110
- const csrf = await this.getCSRF();
233
+ let csrf = await this.getCSRF();
111
234
  if (!csrf) {
112
235
  const message = 'Failed to get CSRF nonce';
113
236
  console.error(message);
114
237
  throw new Error(message);
115
238
  }
116
- const response = await this.sendRequest(csrf, payload);
239
+ /// Added for Session reuse - ET-390 - Starts
240
+ // const response = await this.sendRequest(csrf, payload);
241
+ let response = await this.sendRequest(csrf, payload);
242
+ if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
243
+ console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
244
+ csrf = await this.getCSRF(true);
245
+ response = await this.sendRequest(csrf, payload);
246
+ }
247
+ // Added for Session reuse - ET-390 - Ends
117
248
  const status = response.status;
118
249
  if (status >= 300) {
119
250
  const message = 'Error sending data to FlexPLM:status: ' + response.status;
@@ -166,8 +297,20 @@ class FlexPLMConnect {
166
297
  const urlContext = includeUrlContext ? this.config.urlContext : '';
167
298
  const path = urlPath || ('/servlet/rest' + this.vibeEventEndpoint);
168
299
  const vibeEventsURL = this.config.apiHost + urlContext + path;
169
- const csrfOptions = this.getRequestOptions('GET');
170
- const response = await fetch(vibeEventsURL, csrfOptions);
300
+ // Added for Session reuse - ET-390 - Starts
301
+ const cached = this.getCachedSession();
302
+ const csrfOptions = this.getRequestOptions('GET', cached);
303
+ let response = await fetch(vibeEventsURL, csrfOptions);
304
+ if (cached && this.sessionOptions.retryStatuses.includes(response.status)) {
305
+ this.clearSession();
306
+ response = await fetch(vibeEventsURL, this.getRequestOptions('GET'));
307
+ }
308
+ if (this.sessionOptions.enabled) {
309
+ const cachedCookie = this.extractSessionCookie(response) ?? cached;
310
+ if (cachedCookie)
311
+ this.storeSession(cachedCookie);
312
+ }
313
+ // Added for Session reuse - ET-390 - Ends
171
314
  if (response.status >= 300) {
172
315
  const message = 'Error connecting to FlexPLM:status: ' + response.status;
173
316
  console.error(message);
@@ -28,6 +28,27 @@ const createConfig = (overrides) => ({
28
28
  useDistinctRestEndPointForImages: false,
29
29
  ...overrides,
30
30
  });
31
+ // Added for Session reuse - ET-390 - Starts
32
+ const csrfBody = { items: [{ attributes: { nonce_key: 'CSRF_NONCE', nonce: 'n1' } }] };
33
+ // Response with Set-Cookie support. setCookie = list of raw Set-Cookie header lines.
34
+ const resp = (status, setCookie = [], json = csrfBody) => ({
35
+ status,
36
+ json: jest.fn().mockResolvedValue(json),
37
+ text: jest.fn().mockResolvedValue('error text'),
38
+ headers: { getSetCookie: () => setCookie, get: () => null },
39
+ });
40
+ let userCounter = 0;
41
+ const uniqueUser = () => 'sess-user-' + (++userCounter);
42
+ // The connector config is flat: keys look like 'flexplmConnect.sessionReuse.enabled'
43
+ const sessionConfig = (user, sessionReuse = { enabled: true }) => {
44
+ const flat = {};
45
+ Object.entries(sessionReuse).forEach(([k, v]) => { flat[`flexplmConnect.sessionReuse.${k}`] = v; });
46
+ return createConfig({ userName: () => user, ...flat });
47
+ };
48
+ const fetchMock = () => global.fetch;
49
+ const callHeaders = (i) => fetchMock().mock.calls[i][1].headers;
50
+ const callMethod = (i) => fetchMock().mock.calls[i][1].method;
51
+ // Added for Session reuse - ET-390 - Ends
31
52
  describe('FlexPLMConnect.getRequest', () => {
32
53
  it('should call default URL with urlContext when no params provided', async () => {
33
54
  const connect = new flexplm_connect_1.FlexPLMConnect(createConfig());
@@ -121,3 +142,249 @@ describe('FlexPLMConnect.sendRequest', () => {
121
142
  consoleInfoSpy.mockRestore();
122
143
  });
123
144
  });
145
+ // Added for Session reuse - ET-390 - Starts
146
+ describe('FlexPLMConnect session reuse', () => {
147
+ const payload = { id: '123' };
148
+ it('captures JSESSIONID from the csrf GET and sends it on the POST', async () => {
149
+ const u = uniqueUser();
150
+ fetchMock()
151
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/; HttpOnly']))
152
+ .mockResolvedValueOnce(resp(200, [], {}));
153
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
154
+ expect(fetchMock()).toHaveBeenCalledTimes(2);
155
+ expect(callHeaders(0).Cookie).toBeUndefined(); // first ever call: no cached session
156
+ expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
157
+ expect(callHeaders(1).CSRF_NONCE).toBe('n1');
158
+ });
159
+ it('reuses the cached session on the next event (new FlexPLMConnect instance)', async () => {
160
+ const u = uniqueUser();
161
+ fetchMock()
162
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/'])) // event 1 GET
163
+ .mockResolvedValueOnce(resp(200, [], {})) // event 1 POST
164
+ .mockResolvedValueOnce(resp(200, [])) // event 2 GET (valid session -> no Set-Cookie)
165
+ .mockResolvedValueOnce(resp(200, [], {})); // event 2 POST
166
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
167
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
168
+ expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1'); // GET reuses it
169
+ expect(callHeaders(3).Cookie).toBe('JSESSIONID=abc.tomcat1'); // POST reuses it
170
+ });
171
+ it('replaces the cached session when Windchill answers the GET with a new Set-Cookie', async () => {
172
+ const u = uniqueUser();
173
+ fetchMock()
174
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/']))
175
+ .mockResolvedValueOnce(resp(200, [], {}))
176
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/'])) // old one was stale -> new issued
177
+ .mockResolvedValueOnce(resp(200, [], {}))
178
+ .mockResolvedValueOnce(resp(200, []))
179
+ .mockResolvedValueOnce(resp(200, [], {}));
180
+ const connect = () => new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
181
+ await connect().sendToFlexPLM(payload);
182
+ await connect().sendToFlexPLM(payload);
183
+ await connect().sendToFlexPLM(payload);
184
+ expect(callHeaders(2).Cookie).toBe('JSESSIONID=old.tomcat1'); // event 2 GET sent the old one
185
+ expect(callHeaders(3).Cookie).toBe('JSESSIONID=new.tomcat1'); // POST uses the replacement
186
+ expect(callHeaders(4).Cookie).toBe('JSESSIONID=new.tomcat1'); // event 3 GET sends the replacement
187
+ });
188
+ it('retries once with a new session when the POST is rejected with 403', async () => {
189
+ const u = uniqueUser();
190
+ fetchMock()
191
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/'])) // GET
192
+ .mockResolvedValueOnce(resp(403, [], {})) // POST rejected
193
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/'])) // GET again, fresh session
194
+ .mockResolvedValueOnce(resp(200, [], { ok: true })); // POST succeeds
195
+ const result = await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
196
+ expect(fetchMock()).toHaveBeenCalledTimes(4);
197
+ expect(callHeaders(2).Cookie).toBeUndefined(); // retry GET must NOT send the stale cookie
198
+ expect(callHeaders(3).Cookie).toBe('JSESSIONID=new.tomcat1');
199
+ expect(result.status).toBe(200);
200
+ expect(result.data).toEqual({ ok: true });
201
+ });
202
+ it('also retries on 401', async () => {
203
+ const u = uniqueUser();
204
+ fetchMock()
205
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
206
+ .mockResolvedValueOnce(resp(401, [], {}))
207
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
208
+ .mockResolvedValueOnce(resp(200, [], {}));
209
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
210
+ expect(fetchMock()).toHaveBeenCalledTimes(4);
211
+ });
212
+ it('does not loop: a second 403 after the retry is surfaced as an error', async () => {
213
+ const u = uniqueUser();
214
+ fetchMock()
215
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1']))
216
+ .mockResolvedValueOnce(resp(403, [], {}))
217
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1']))
218
+ .mockResolvedValueOnce(resp(403, [], {}));
219
+ await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload))
220
+ .rejects.toThrow('Error sending data to FlexPLM:status: 403');
221
+ expect(fetchMock()).toHaveBeenCalledTimes(4);
222
+ });
223
+ it('does not retry on non-auth errors such as 500 (event may already be processed)', async () => {
224
+ const u = uniqueUser();
225
+ fetchMock()
226
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
227
+ .mockResolvedValueOnce(resp(500, [], {}));
228
+ await expect(new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload))
229
+ .rejects.toThrow('Error sending data to FlexPLM:status: 500');
230
+ expect(fetchMock()).toHaveBeenCalledTimes(2);
231
+ });
232
+ it('retries the csrf GET without a cookie when the cached session is rejected there', async () => {
233
+ const u = uniqueUser();
234
+ fetchMock()
235
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1'])) // event 1 GET
236
+ .mockResolvedValueOnce(resp(200, [], {})) // event 1 POST
237
+ .mockResolvedValueOnce(resp(401, [])) // event 2 GET with cached cookie rejected
238
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1'])) // event 2 GET retry, no cookie
239
+ .mockResolvedValueOnce(resp(200, [], {})); // event 2 POST
240
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
241
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
242
+ expect(callHeaders(2).Cookie).toBe('JSESSIONID=old.tomcat1');
243
+ expect(callHeaders(3).Cookie).toBeUndefined();
244
+ expect(callHeaders(4).Cookie).toBe('JSESSIONID=new.tomcat1');
245
+ });
246
+ it('expires the cached session after ttlSeconds', async () => {
247
+ const u = uniqueUser();
248
+ const realNow = Date.now();
249
+ const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(realNow);
250
+ fetchMock()
251
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
252
+ .mockResolvedValueOnce(resp(200, [], {}))
253
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=def.tomcat1']))
254
+ .mockResolvedValueOnce(resp(200, [], {}));
255
+ const cfg = sessionConfig(u, { enabled: true, ttlSeconds: 1 });
256
+ await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
257
+ nowSpy.mockReturnValue(realNow + 2000); // 2s later > 1s ttl
258
+ await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
259
+ expect(callHeaders(2).Cookie).toBeUndefined(); // expired -> GET sends no cookie
260
+ expect(callHeaders(3).Cookie).toBe('JSESSIONID=def.tomcat1');
261
+ nowSpy.mockRestore();
262
+ });
263
+ it('uses the last JSESSIONID when several Set-Cookie lines are returned', async () => {
264
+ const u = uniqueUser();
265
+ fetchMock()
266
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=first.tomcat1; Path=/', 'OTHER=x; Path=/', 'JSESSIONID=second.tomcat1; Path=/']))
267
+ .mockResolvedValueOnce(resp(200, [], {}));
268
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
269
+ expect(callHeaders(1).Cookie).toBe('JSESSIONID=second.tomcat1');
270
+ });
271
+ it('falls back to headers.get("set-cookie") when getSetCookie is not available', async () => {
272
+ const u = uniqueUser();
273
+ const legacy = {
274
+ status: 200,
275
+ json: jest.fn().mockResolvedValue(csrfBody),
276
+ text: jest.fn(),
277
+ headers: { get: (k) => (k.toLowerCase() === 'set-cookie' ? 'JSESSIONID=legacy.tomcat1; Path=/' : null) },
278
+ };
279
+ fetchMock().mockResolvedValueOnce(legacy).mockResolvedValueOnce(resp(200, [], {}));
280
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
281
+ expect(callHeaders(1).Cookie).toBe('JSESSIONID=legacy.tomcat1');
282
+ });
283
+ it('honours a custom cookieName', async () => {
284
+ const u = uniqueUser();
285
+ fetchMock()
286
+ .mockResolvedValueOnce(resp(200, ['MYSESSION=zzz; Path=/', 'JSESSIONID=ignored; Path=/']))
287
+ .mockResolvedValueOnce(resp(200, [], {}));
288
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: true, cookieName: 'MYSESSION' })).sendToFlexPLM(payload);
289
+ expect(callHeaders(1).Cookie).toBe('MYSESSION=zzz');
290
+ });
291
+ it('accepts enabled as the string "true"', async () => {
292
+ const u = uniqueUser();
293
+ fetchMock()
294
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
295
+ .mockResolvedValueOnce(resp(200, [], {}));
296
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: 'true' })).sendToFlexPLM(payload);
297
+ expect(callHeaders(1).Cookie).toBe('JSESSIONID=abc.tomcat1');
298
+ });
299
+ it('keeps separate sessions per user', async () => {
300
+ const a = uniqueUser();
301
+ const b = uniqueUser();
302
+ fetchMock()
303
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=aaa.tomcat1']))
304
+ .mockResolvedValueOnce(resp(200, [], {}))
305
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=bbb.tomcat1']))
306
+ .mockResolvedValueOnce(resp(200, [], {}));
307
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(a)).sendToFlexPLM(payload);
308
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(b)).sendToFlexPLM(payload);
309
+ expect(callHeaders(2).Cookie).toBeUndefined(); // user b must not see user a's cookie
310
+ expect(callHeaders(3).Cookie).toBe('JSESSIONID=bbb.tomcat1');
311
+ });
312
+ it('never logs the cookie value', async () => {
313
+ const isInfoOn = jest.spyOn(app_framework_1.Logger, 'isInfoOn').mockReturnValue(true);
314
+ const info = jest.spyOn(console, 'info').mockImplementation();
315
+ const u = uniqueUser();
316
+ fetchMock()
317
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=supersecret.tomcat1']))
318
+ .mockResolvedValueOnce(resp(200, [], {}))
319
+ .mockResolvedValueOnce(resp(200, []))
320
+ .mockResolvedValueOnce(resp(200, [], {}));
321
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload);
322
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u)).sendToFlexPLM(payload); // 2nd event sends Cookie on GET and POST
323
+ const logged = info.mock.calls.map(c => String(c[0] ?? '')).join('\n');
324
+ expect(logged).toContain('"Cookie":"***masked***"');
325
+ expect(logged).not.toContain('supersecret');
326
+ isInfoOn.mockRestore();
327
+ info.mockRestore();
328
+ });
329
+ });
330
+ describe('FlexPLMConnect session reuse - feature disabled (default)', () => {
331
+ const payload = { id: '123' };
332
+ it('sends no Cookie header and makes exactly one GET + one POST', async () => {
333
+ const u = uniqueUser();
334
+ fetchMock()
335
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // Set-Cookie present but must be ignored
336
+ .mockResolvedValueOnce(resp(200, [], {}))
337
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=def.tomcat1']))
338
+ .mockResolvedValueOnce(resp(200, [], {}));
339
+ const cfg = createConfig({ userName: () => u }); // no flexplmConnect at all
340
+ await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
341
+ await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
342
+ for (let i = 0; i < 4; i++) {
343
+ expect(callHeaders(i).Cookie).toBeUndefined();
344
+ }
345
+ });
346
+ it('does not retry on 403 (behaves exactly as before)', async () => {
347
+ const u = uniqueUser();
348
+ fetchMock()
349
+ .mockResolvedValueOnce(resp(200))
350
+ .mockResolvedValueOnce(resp(403, [], {}));
351
+ await expect(new flexplm_connect_1.FlexPLMConnect(createConfig({ userName: () => u })).sendToFlexPLM(payload))
352
+ .rejects.toThrow('Error sending data to FlexPLM:status: 403');
353
+ expect(fetchMock()).toHaveBeenCalledTimes(2);
354
+ });
355
+ it('explicit enabled:false behaves the same as not configured', async () => {
356
+ const u = uniqueUser();
357
+ fetchMock()
358
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
359
+ .mockResolvedValueOnce(resp(200, [], {}));
360
+ await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: false })).sendToFlexPLM(payload);
361
+ expect(callHeaders(1).Cookie).toBeUndefined();
362
+ });
363
+ });
364
+ describe('FlexPLMConnect.getRequest session reuse (only if you applied step 2g)', () => {
365
+ it('sends the cached cookie on image/GET requests', async () => {
366
+ const u = uniqueUser();
367
+ fetchMock()
368
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // csrf GET primes the cache
369
+ .mockResolvedValueOnce(resp(200, [], {})) // POST
370
+ .mockResolvedValueOnce(resp(200, [], { items: [] })); // getRequest
371
+ const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
372
+ await connect.sendToFlexPLM({ id: '1' });
373
+ await connect.getRequest();
374
+ expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
375
+ });
376
+ it('retries once without the cookie when the cached session is rejected on getRequest', async () => {
377
+ const u = uniqueUser();
378
+ fetchMock()
379
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
380
+ .mockResolvedValueOnce(resp(200, [], {}))
381
+ .mockResolvedValueOnce(resp(401, [])) // getRequest with cached cookie
382
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1'], { items: [] })); // retry, no cookie
383
+ const connect = new flexplm_connect_1.FlexPLMConnect(sessionConfig(u));
384
+ await connect.sendToFlexPLM({ id: '1' });
385
+ await connect.getRequest();
386
+ expect(callHeaders(2).Cookie).toBe('JSESSIONID=abc.tomcat1');
387
+ expect(callHeaders(3).Cookie).toBeUndefined();
388
+ });
389
+ });
390
+ // Added for Session reuse - ET-390 - Ends
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/flexplm",
3
- "version": "1.7.6",
3
+ "version": "1.7.7-alpha.01fb300",
4
4
  "description": "Library used for integration with flexplm.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",